Using ROLLUP and CUBE for Hierarchical Totals in PostgreSQL
📖 Scenario: You work for a retail company that tracks sales data by region, store, and product category. Your manager wants to see sales totals at different levels: by product category alone, by store and product category, by region and product category, and overall totals.
🎯 Goal: Build SQL queries using ROLLUP and CUBE to calculate hierarchical sales totals for the company.
📋 What You'll Learn
Create a table called
sales with columns region, store, category, and amount.Insert sample sales data with at least 6 rows covering multiple regions, stores, and categories.
Write a query using
GROUP BY ROLLUP(region, store, category) to get hierarchical totals.Write a query using
GROUP BY CUBE(region, store, category) to get all combinations of totals.💡 Why This Matters
🌍 Real World
Retail and sales companies often need to see totals at different levels, such as by store, region, or product category. ROLLUP and CUBE help create these summaries easily.
💼 Career
Understanding how to write SQL queries with ROLLUP and CUBE is useful for data analysts and database developers who prepare reports and dashboards.
Progress0 / 4 steps