GROUP BY GROUPING SETS

constructsupportedQueries & DML

docs.snowflake.com ↗

GROUPING SETS is a powerful extension of the GROUP BY clause that computes multiple GROUP BY clauses in a single statement. A grouping set is a set of dimension columns. GROUPING SETS expressions can be combined with other GROUP BY expressions, making this construct an integrated part of the GROUP BY clause rather than a separate construct. For example, you can write GROUP BY x, GROUPING SETS(y, z) to group by column x in combination with separate groupings on y and z. A GROUPING SETS expression is equivalent to the union of two or more GROUP BY operations in the same result set. For example: - GROUP BY GROUPING SETS((a)) is equivalent to the single grouping set operation GROUP BY a. - GROUP BY GROUPING SETS((a), (b)) is equivalent to GROUP BY a UNION ALL GROUP BY b. Note that GROUPING SETS(a, b) without additional parentheses is logically equivalent to GROUPING SETS((a), (b)) because both create two separate grouping sets, one for column a and one for column b. This expression is quite different from GROUPING SETS((a, b)), which creates a single grouping set that groups by both columns.

Syntax

SELECT ...
FROM ...
[ ... ]
GROUP BY [ groupItem [ , groupItem [ , ... ] ] , ] GROUPING SETS ( groupSet [ , groupSet [ , ... ] ] )
[ ... ]

Where

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

groupSet ::= groupItem | ( groupItem [ , groupItem [ , ... ] ] )

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

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.

See also

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