如何格式化具有多个聚合的结果集?

时间:2018-08-09 08:14:29

标签: sql tsql

鉴于我有下表:

+--------+------------+------+--------+
| Amount |    Date    | Type | UserId |
+--------+------------+------+--------+
|      8 | 2018-08-10 | VL   |     11 |
|      8 | 2018-08-11 | VL   |     11 |
|      8 | 2018-08-12 | VL   |     11 |
|      4 | 2018-08-09 | EL   |      9 |
|      8 | 2018-08-10 | SL   |      9 |
+--------+------------+------+--------+

我们如何格式化结果集以获取相同类型金额的总和? 以及过去所有记录的总和(日期>当前日期)。

类似这样的东西:

 +------+---------------------+----------------+
| Type | TotalScheduledLeave | TotalLeaveUsed |
+------+---------------------+----------------+
| VL   |                  24 |              0 |
| VL   |                  24 |              0 |
| VL   |                  24 |              0 |
| EL   |                  12 |              4 |
| SL   |                  12 |              4 |
+------+---------------------+----------------+

我尝试了以下代码:

SELECT Type
       ,SUM(Amount) as 'TotalScheduledLeave'
       ,CASE WHEN Date > GETUTCDATE()
       THEN SUM(Amount)
       ELSE 0
       END as 'TotalLeaveUsed'
FROM TimeOffTable
WHERE User = @UserId
GROUP BY Type

这将引发错误,因为选择列表中的日期未包含在聚合函数或组子句中。但是,当我尝试对日期进行分组时,我在 'TotalScheduledLeave'

中得到了错误的值

1 个答案:

答案 0 :(得分:2)

尝试一下:

SELECT   Type ,
         SUM(Amount) AS 'TotalScheduledLeave' ,
         SUM(CASE WHEN [Date] > GETUTCDATE() THEN amount
                  ELSE 0
             END) AS 'TotalLeaveUsed'
FROM     TimeOffTable
WHERE    USER = @UserId
GROUP BY Type;