2

我目前有以下 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 表示可收费,false 表示不收费)。我如何合并它来为每种类型的单位显示两个总和?

4

1 回答 1

7

您可以使用 aCASESUM()计算单独的总数:

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;
于 2013-01-23T13:52:19.810 回答