Grouping Functions
Overview
Grouping functions are used to identify grouping levels in GROUP BY extensions (such as ROLLUP, CUBE, and GROUPING SETS). AI DataLake supports the GROUP_ID and GROUPING/GROUPING_ID functions in the SQL standard, which are used to distinguish different group combinations and determine whether a column is involved in the current group aggregation.
For more information, see Grouping Functions.
Application Scenarios
- Multi-level aggregation reports: Identifies different group combinations in multi-level group aggregation, such as ROLLUP, CUBE, and GROUPING SETS.
- Distinguishing subtotals from totals: Uses the GROUPING function to determine whether a column is aggregated in the current group (NULL is returned) to distinguish original data rows from aggregated rows.
- Condition filtering: Uses the GROUPING result in the HAVING clause to filter specific group levels.
Notes and Constraints
- The GROUP_ID and GROUPING/GROUPING_ID functions are only meaningful in GROUP BY statements that contain ROLLUP, CUBE, or GROUPING SETS.
- GROUPING_ID is an alias of GROUPING, and they are semantically equivalent.
- In the bit vector returned by GROUPING, 0 indicates that the corresponding column is involved in GROUP BY, and 1 indicates that the corresponding column is not involved in GROUP BY (the column is aggregated to NULL).
Syntax Structure
| Syntax | Return Type | Description | Example |
|---|---|---|---|
| GROUP_ID() | INTEGER | Returns an integer that uniquely identifies the combination of grouping keys. | -- Used together with ROLLUP to identify each grouping level. SELECT dept, role, GROUP_ID() AS gid, COUNT(*) AS cnt FROM employees GROUP BY ROLLUP(dept, role); -- Example result: -- dept=Sales, role=Manager, gid=0, cnt=5 -- dept=Sales, role=NULL, gid=0, cnt=10 -- dept=NULL, role=NULL, gid=0, cnt=50 |
| GROUPING(expression1 [, expression2]* ) GROUPING_ID(expression1 [, expression2]* ) | INTEGER | Returns a bit vector for the given grouping expression. | -- Used together with ROLLUP to determine whether the grouping key is aggregated. SELECT dept, role, GROUPING(dept, role) AS grp_bits, COUNT(*) AS cnt FROM employees GROUP BY ROLLUP(dept, role); -- Example result: -- dept=Sales, role=Manager, grp_bits=0, cnt=5 -- dept=Sales, role=NULL, grp_bits=1, cnt=10 -- dept=NULL, role=NULL, grp_bits=3, cnt=50 -- Uses CASE WHEN to distinguish aggregation levels. SELECT CASE WHEN GROUPING (dept, role) = 0 THEN 'Details' WHEN GROUPING(dept, role) = 1 THEN 'Department subtotal' WHEN GROUPING (dept, role) = 3 THEN 'Total' END AS level, dept, role, COUNT(*) AS cnt FROM employees GROUP BY ROLLUP(dept, role); |
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot