2013-01-23 110 views
0

我有以下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 x Summa [Units] one對於Chargeable = true,另一個對於Chargeable = false。這兩個表通過ChargeCode鏈接,它出現在tblTimesheetEntries和tblChargeCodes中。

回答

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; 
+0

+1。 。 。打我吧;) –

+0

再次感謝你Bluefeet :) – PJW

+0

@PJW歡迎您! :) – Taryn