显示SQL Server查询结果中的子总计

时间:2018-01-16 12:21:46

标签: sql sql-server tsql sql-server-2014

SELECT 
    BCD.[EventID],
    M.TargetCategory,
    BCD.[RoundName],
    COUNT(CASE
             WHEN R.Status_Id <> 4
                THEN 1
                ELSE NULL
          END) AS [Outstanding Events]
FROM 
    [dbo].[Event_Details] BCD
LEFT JOIN 
    [dbo].[lkpTarget] M ON BCD.TargetID = M.TargetID
LEFT JOIN 
    [dbo].[EventComments] R ON BCD.EventID = R.[EventID]
GROUP BY 
    BCD.[EventID], M.TargetCategory, BCD.[RoundName]
HAVING 
    COUNT(CASE
             WHEN R.Status_Id <> 4
                THEN 1
                ELSE NULL
          END) > 0
ORDER BY 
    TargetCategory ASC;

我上面的查询显示了每个[Outstanding Events]的{​​{1}}。

是否有人知道我可以修改上述查询的最佳方式,以便我可以显示RoundName分组的[Outstanding Events]小计,然后显示整个查询结果的TargetCategory总计?

1 个答案:

答案 0 :(得分:4)

使用grouping sets

GROUP BY GROUPING SETS ( (BCD.[EventID], M.TargetCategory, BCD.[RoundName]),
                         (BCD.[RoundName]),
                         ()
                       )