GROUP BY ROLLUP

constructsupportedQueries & DML

docs.snowflake.com ↗

GROUP BY ROLLUP is an extension of the GROUP BY clause that produces aggregated rows at multiple levels of a hierarchy (in addition to the detailed grouped rows). For example, if you group by city and state, ROLLUP produces aggregations for each city/state combination, each state total, and a grand total across all states. These aggregations are computed using the same aggregate functions specified in the SELECT clause. ROLLUP can be combined with other GROUP BY expressions. For example, you can write GROUP BY x, ROLLUP(y, z) to group by column x in combination with rollup aggregations on y and z. You can think of rollup as generating multiple result sets, each of which (after the first) is the aggregate of the previous result set. So, for example, if you own a chain of retail stores, you might want to see the profit for: - Each store. - Each city (large cities might have multiple stores). - Each state. - Everything (all stores in all states). You could create separate reports to get that information, but it is more efficient to scan the data once. If you are familiar with the concept of grouping sets, you can think of a ROLLUP grouping as equivalent to a series of grouping sets, but essentially a shorter specification. The N elements of a ROLLUP specification correspond to N+1 GROUPING SETS.

Syntax

SELECT ...
FROM ...
[ ... ]
GROUP BY [ groupItem [ , groupItem [ , ... ] ] , ] ROLLUP ( groupItem [ , groupItem [ , ... ] ] )
[ ... ]

Where

groupItem ::= { <column_alias> | <position> | <expr> }

Parameters

NameRequiredDescription
column_aliasColumn alias appearing in the query block’s SELECT list.
positionPosition of an expression in the SELECT list.
exprAny expression on tables in the current scope.

Usage notes

See also

- GROUPING (Utility function to identify which grouping level produced each row) - GROUP BY GROUPING SETS - GROUP BY CUBE

Parameters

column_alias: Column alias appearing in the query block’s SELECT list. position: Position of an expression in the SELECT list. expr: Any expression on tables in the current scope.