Part 56: Advanced Grouping: GROUPING SETS for Flexible Reporting
Instead of running 3 separate queries combined with UNION ALL, GROUPING SETS computes multiple aggregations in a single table pass.
1. Syntax
SELECT brand, category, SUM(revenue) AS total_revenue
FROM sales
GROUP BY GROUPING SETS (
(brand, category), -- Subtotal by brand and category
(brand), -- Subtotal by brand
() -- Grand total
);
Key Takeaways
GROUPING SETSeliminates redundant queries and table scans in analytics reporting.
In Part 57, we will explore Advanced Grouping: ROLLUP for Subtotals and Grand Totals!

