我目前有以下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;
返回给定用户和日期的总计[单位]。
但是,我想根据新标准生成两个单独的总单位,即[单位]是否“可收费或不收费”。 tblTimeSheets中有一个名为Chargeable的字段,它是一个布尔值(对于可收费,则为true,对于不收费,则为false)。如何将其合并为每种类型的单位显示两个和?
答案 0 :(得分:7)
您可以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;