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;