CUBE: like an Excel pivot table but inside SQL
In SQL, GROUP BY CUBE
is a powerful grouping mechanism used to generate subtotals and grand totals for a dataset across multiple dimensions. It essentially computes all possible combinations of groupings for the specified columns.
Here’s an example:
Let’s say you have a table called Sales
with the following structure:
You want to compute subtotals for each combination of Region
and Product
, as well as the grand total for all sales.
Result:
GROUP BY CUBE (Region, Product)
generates all combinations ofRegion
andProduct
, including:Individual values of
Region
andProduct
.Subtotals for each
Region
(irrespective ofProduct
).Subtotals for each
Product
(irrespective ofRegion
).A grand total (ignoring both
Region
andProduct
).
NULL values in the output represent groupings where the column is not considered in that particular subtotal or total. For example:
Region = NULL
andProduct = Widget A
is the subtotal for all regions forWidget A
.Region = NULL
andProduct = NULL
is the grand total.
GROUP BY CUBE
is especially useful for generating reports and summaries.