ROLLUP is an extension to GROUP BY that enables calculation of multiple levels of subtotals across a specified group of attributes. It also calculates a grand total.
ROLLUP(a, b, c) = GROUPING SETS((a,b,c), (a,b), (a), ())
For instance, if a query specifies ROLLUP on attributes of time, region, and department (n=3), the result set will include rows at four aggregation levels.
In summary, ROLLUP is intended for use in tasks involving subtotals.
GROUP BY ROLLUP(attributeList)where attributeList is either a single attribute or a comma-separated list of multiple attributes. The attributes may be single-assign or multi-assign attributes. ROLLUP can be used on collections.
DEFINE Resellers AS SELECT DimReseller_AnnualSales AS Sales, DimGeography_CountryRegionName AS Countries, DimGeography_StateProvinceName AS States, DimReseller_OrderMonth AS OrderMonth FROM ResellerState WHERE DimReseller_OrderMonth IS NOT NULL; RETURN ResellerSales AS SELECT SUM(Sales) AS TotalSales FROM Resellers GROUP BY ROLLUP(Countries, States, OrderMonth)
GROUP BY expr1, ROLLUP(expr2, expr3)
In this case, the GROUP BY clause creates subtotals at (2+1=3) aggregation levels. That is, at level (expr1, expr2, expr3), (expr1, expr2), and (expr1).
DEFINE Resellers AS SELECT ... RETURN ResellerSales AS SELECT SUM(Sales) AS TotalSales FROM Resellers GROUP BY Countries, ROLLUP(States, OrderMonth)