我目前有以下sql查询
SELECT [Date], DATENAME(dw,[Date]) AS Day, SUM(Units) AS TotalUnits FROM tblTimesheetEntries WHERE UserID = 'PJW' AND Date >= '2013-01-01' GROUP BY [Date] ORDER BY [Date] DESC;
它返回给定用户和日期的总计[单位]。
但是,我想根据新的标准(即[Units]是否在“可充电”位置)来生成两个单独的总计单位。tblTimeSheets中有一个称为Chargeable的字段,它是一个布尔值(true表示chargeable,false表示false)。如何将其合并为每种类型的单位显示两个总和?
您可以将CASE与一起使用SUM()来计算单独的总计:
CASE
SUM()
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;