简体   繁体   中英

Showing Sub totals in SQL Server query results

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;

I have the above query showing the [Outstanding Events] for each RoundName .

Does anyone know the best way I can modify the above query such that I can show [Outstanding Events] sub totals grouped by TargetCategory and then an [Outstanding Events] grand total for the entire query result?

Use grouping sets :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM