Subtotals and Grand Totals with ROLLUP in SQL
ROLLUP adds total rows to a grouped result, so a report carries its own subtotals and grand total.
A grouped report often needs a total row at the bottom. GROUP BY ROLLUP (…) adds it for you: alongside the normal per-group rows, it emits an extra row that aggregates across all groups.
In that total row, the grouped column is NULL because there is no single category it belongs to. Use coalesce() to give it a readable label, and grouping() to sort it to the bottom.
select region, sum(amount) as total
from sales
group by rollup (region)With more than one grouping column, ROLLUP (a, b) also produces per-a subtotals, not just the grand total. You get a full hierarchy of totals from one query.
Schema · Garden ShopTable · order_items5 columns · 48 rows
One row per line item within an order.
Report total revenue (quantity * unit_price) per category, with a grand-total row at the bottom labelled'All categories'. Return category andrevenue.
- Columns: category, revenue.
- Rows: 8 category rows plus 1 grand-total row (9 total).
- The 'All categories' revenue equals the sum of the eight category rows.
Related
Split a group into side-by-side columns with FILTER.
Roll a group's values into one comma-separated cell.
Group on a CASE expression to bucket values.
Return several subtotal levels in one grouped query.