GROUPING SETS and CUBE in SQL
GROUPING SETS lists several GROUP BY levels in one query; CUBE returns every combination of them.
ROLLUP builds a hierarchy of subtotals: category, then category plus supplier, then a grand total. But sometimes you want totals for two dimensionsindependently: a breakdown by category and a separate breakdown by supplier without the nested combinations.
GROUPING SETS gives you exactly that control: you list each grouping level you want, and the empty set () adds the grand total. CUBE is the shortcut for "every combination of these dimensions".
select region, product, sum(amount) as total
from sales
group by grouping sets ((region), (product), ())
-- ROLLUP(region, product) = a hierarchy of subtotals
-- CUBE(region, product) = every combination of subtotalsLabeling the subtotal rows
On a per-supplier row there is no single category, so category_name comes back as NULL. Wrap each dimension in coalesce() to give those subtotal rows a readable label like "All categories".
Schema · Garden ShopTable · products9 columns · 24 rows
One row per product, with price, cost, and inventory levels.
In one query, count products by category,by supplier, and overall. Label the subtotal rows "All categories" and "All suppliers" so every row reads clearly.
- Columns: category, supplier, product_count.
- Eight per-category rows, five per-supplier rows, and one grand-total row (14 rows).
- ROLLUP is a hierarchy; GROUPING SETS lets you pick independent levels, and CUBE returns every combination.
Related
Split a group into side-by-side columns with FILTER.
Add subtotal and total rows to a grouped report.
Roll a group's values into one comma-separated cell.
Group on a CASE expression to bucket values.