SQL查询:无法对子查询执行聚合函数

时间:2013-01-23 14:18:16

标签: sql

我有以下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中使用子查询。

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

1 个答案:

答案 0 :(得分: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;