0

我有以下 SQL 查询

SELECT
   [Date], 
   DATENAME(dw,[Date]) AS Day, 
   SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 1) THEN Units ELSE 0 END) ChargeableTotal,
   SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 0) THEN Units ELSE 0 END) NotChargeableTotal,
   SUM(Units) AS TotalUnits
FROM 
   tblTimesheetEntries 
WHERE 
   UserID = 'PJW' 
   AND Date >= '2013-01-01' 
GROUP BY 
   [Date] 
ORDER BY 
   [Date] DESC;

但我收到错误消息:

无法对包含聚合或子查询的表达式执行聚合函数。

因为我在 Case Else Summation 中使用子查询。

如何修改我的查询以获得 [Units] 的 2 个总和,一个用于 Chargeable = true,一个用于 Chargeable = false,即使 Chargeable 字段与所有其他信息位于不同的表中。这两个表由出现在 tblTimesheetEntries 和 tblChargeCodes 中的 ChargeCode 链接。

4

1 回答 1

5

您是否尝试过加入以下表格chargeCode

SELECT e.[Date], 
  DATENAME(dw,e.[Date]) AS Day, 
  SUM(CASE WHEN c.Chargeable = 1 THEN e.Units ELSE 0 END) ChargeableTotal,
  SUM(CASE WHEN c.Chargeable = 0 THEN e.Units ELSE 0 END) NotChargeableTotal,
  SUM(e.Units) AS TotalUnits
FROM tblTimesheetEntries e
LEFT JOIN tblChargeCodes c
  on e.ChargeCode = c.ChargeCode
WHERE e.UserID = 'PJW' 
  AND e.Date >= '2013-01-01' 
GROUP BY e.[Date] 
ORDER BY e.[Date] DESC;
于 2013-01-23T14:22:05.817 回答