SQL Query: Including Two Sums based on different criteria from the same table

前端 未结 1 1418
感情败类
感情败类 2021-01-22 10:43

I currently have the following sql query

SELECT [Date], DATENAME(dw,[Date]) AS Day, SUM(Units) AS TotalUnits
FROM tblTimesheetEntries 
WHERE UserID = \'PJW\' 
AN         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 11:03

    You can use a CASE with the SUM() to calculate the separate totals:

    SELECT [Date], 
        DATENAME(dw,[Date]) AS Day, 
        sum(case when Chargeable = 1 then Units else 0 end) ChargeableTotal,
        sum(case when 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;
    

    0 讨论(0)
提交回复
热议问题