Aggregation
ROLLUP and grouping sets
Add a grand total to grouped order counts without confusing it with a NULL source value.
Lesson 30 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Add a grand total to grouped order counts without confusing it with a NULL source value.
Run the example
sql
SELECT CASE WHEN GROUPING(OrderStatus) = 1 THEN N'All statuses'
ELSE OrderStatus END AS StatusGroup,
COUNT(*) AS OrderCount
FROM dbo.Orders
GROUP BY ROLLUP (OrderStatus)
ORDER BY GROUPING(OrderStatus), OrderStatus;Read it step by step
- ROLLUP(OrderStatus) produces one group per status plus a grand-total group.
- GROUPING(OrderStatus) distinguishes the grand-total marker from an actual NULL status.
- ORDER BY places the individual statuses before the total row.
Check the result
| StatusGroup | OrderCount |
|---|---|
| Cancelled | 1250 |
| Completed | 1250 |
| Pending | 1250 |
| Shipped | 1250 |
| All statuses | 5000 |
The status counts sum to the grand total; the source OrderStatus column is NOT NULL.
Practice
Count orders by OrderChannel and add a grand total using GROUPING SETS.
Check your answer and expected result
Reveal answer
sql
SELECT CASE WHEN GROUPING(OrderChannel) = 1 THEN N'All channels'
ELSE OrderChannel END AS ChannelGroup,
COUNT(*) AS OrderCount
FROM dbo.Orders
GROUP BY GROUPING SETS ((OrderChannel), ())
ORDER BY GROUPING(OrderChannel), OrderChannel;| ChannelGroup | OrderCount |
|---|---|
| InStore | 1666 |
| Online | 3334 |
| All channels | 5000 |
The two channel counts sum to the All channels row.
Your progress
Reveal the check answer or reach the end to complete this lesson.