Advanced Aggregation withROLLUP

Uses GROUP BY ROLLUP and GROUPING to generate hierarchical summary rows with subtotals and grand totals for multi-dimensional analysis.

SqlData Fetching

Code

snippet
SELECT
    CASE WHEN GROUPING(region) = 1 THEN 'ALL REGIONS' ELSE region END AS region,
    CASE WHEN GROUPING(category) = 1 THEN 'ALL CATEGORIES' ELSE category END AS category,
    COUNT(*) AS order_count,
    SUM(amount) AS total_sales,
    AVG(amount) AS avg_sale
FROM sales
GROUP BY ROLLUP (region, category)
ORDER BY region, category;

How the snippet works

The statement is SELECT, touching sales.

Concretely, the SQL combines: COUNT, SUM, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run the statement against the sales table.

Statements that matter

SELECT
CASE WHEN GROUPING(region) = 1 THEN 'ALL REGIONS' ELSE region END AS region,
CASE WHEN GROUPING(category) = 1 THEN 'ALL CATEGORIES' ELSE category END AS category,
COUNT(*) AS order_count,
SUM(amount) AS total_sales,
AVG(amount) AS avg_sale
FROM sales
GROUP BY ROLLUP (region, category)
ORDER BY region, category;

FAQ

Which tables does the SQL touch?
`sales`.