Complete the code to calculate hierarchical totals using ROLLUP.
SELECT department, product, SUM(sales) FROM sales_data GROUP BY [1];The ROLLUP function creates hierarchical totals by grouping first by department, then product, and finally a grand total.
Complete the code to calculate all combinations of totals using CUBE.
SELECT region, category, SUM(amount) FROM sales GROUP BY [1];The CUBE function generates all possible combinations of grouping columns, giving totals for each combination.
Fix the error in the GROUP BY clause to correctly use ROLLUP.
SELECT category, subcategory, SUM(revenue) FROM sales_data GROUP BY [1];To get hierarchical totals, the GROUP BY clause must use ROLLUP(category, subcategory) instead of just listing columns.
Fill both blanks to create a query that uses CUBE and filters out grand totals.
SELECT region, product, SUM(sales) FROM sales_data GROUP BY [1] HAVING GROUPING([2]) = 0;
Using CUBE(region, product) groups all combinations. The GROUPING(region) = 0 condition filters out rows where region is a subtotal or grand total.
Fill all three blanks to write a query that uses ROLLUP and shows which rows are subtotals or totals.
SELECT department, team, SUM(profit), GROUPING([1]) AS dept_grouping, GROUPING([2]) AS team_grouping FROM profits GROUP BY [3];
This query uses ROLLUP(department, team) to get hierarchical totals. The GROUPING() function shows if a row is a subtotal or total for each column.