SQL查询:根据同一个表中的不同条件包含两个总和

时间:2013-01-23 13:49:09

标签: sql

我目前有以下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)。如何将其合并为每种类型的单位显示两个和?

1 个答案:

答案 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;