GROUP BY CUBE
constructsupportedQueries & DMLGROUP BY CUBE is an extension of the GROUP BY clause, similar to GROUP BY ROLLUP. Like ROLLUP, CUBE produces aggregated rows at multiple levels. However, while ROLLUP creates aggregations that follow a natural hierarchy (for example, city rolls up to state, and state rolls up to country), CUBE creates aggregations for all possible combinations of the specified columns. These include both the hierarchical aggregations that ROLLUP would produce and additional “cross-tabulation” rows that aggregate across each individual dimension independently. CUBE can be combined with other GROUP BY expressions. For example, you can write GROUP BY x, CUBE(y, z) to group by column x in combination with cube aggregations on y and z. A CUBE grouping is equivalent to a series of grouping sets and is essentially a shorter specification. The N elements of a CUBE specification correspond to 2^N GROUPING SETS.
Syntax
SELECT ...
FROM ...
[ ... ]
GROUP BY [ groupItem [ , groupItem [ , ... ] ] , ] CUBE ( groupItem [ , groupItem [ , ... ] ] )
[ ... ]
Where
groupItem ::= { <column_alias> | <position> | <expr> }
Parameters
| Name | Required | Description |
|---|---|---|
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. |
Usage notes
- Snowflake allows up to 7 elements (equivalent to 128 grouping sets) in each cube.
See also
- GROUPING (Utility function to identify which grouping level produced each row) - GROUP BY GROUPING SETS - GROUP BY ROLLUP
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.