Add a summary row with totals
For a quick win, define your query for data and then append a totals row using UNION ALL and SUM. Here's how you would do it:
It will give you customers, their sales amounts, and a final row with the grand total.
Adding subtotals using rollup
You can add subtotals to your results with ROLLUP, a modifier of GROUP BY, if your DBMS supports it.
This gets you your subtotal rows. The NULL in the result indicates the grand total. To distinguish these NULLs from your data NULLs, use GROUPING().
Null-proofing and ordering rows
Nulls can cause chaos in your summary rows. Make your output shipshape by using ISNULL() or COALESCE()* to handle NULL values:
To decide the placement of summary rows, put a column for ordering:
This ensures grand total row is seated at the bottom, where it can observe its kingdom.
Using grouping sets for dynamic aggregation
For more layered aggregation, GROUPING SETS are your wizards-in-arms:
This allows inclusion of summary totals across different groupings without disturbing the original data.
What's next after rollup and grouping
For complete control on summary rows, refer to the official documentation or trusted blogs on ROLLUP and GROUPING().
In complex scenarios, you might have to bring together various methods like GROUP BY GROUPING SETS or UNION ALL along with subqueries.
Going beyond rollup
At times, you may need information that goes beyond ROLLUP:
- Selective totals: If you want to decide which totals show, use
UNION ALLwith a subquery. - Custom groupings: If
GROUP BYisn't binding your data well, aCASEstatement can give bespoke groupings.
Was this article helpful?