Grouping sets
GROUPING SETS () syntax offers a generalization
of the rollup and cube capability. Any rollup() or cube() operation can be translated into a
grouping sets specification. The syntax is as follows:GROUP BY [<set quantifier>] GROUPING SETS(<grouping-set-list>);<set quantifier> is either DISTINCT or
ALL and defaults to ALL, and <grouping-set-list> is a comma-separated list of grouping sets, each of which is a parenthesized <grouping-col-list>, as in the following example:SELECT col1, col2, col3, COUNT(*) FROM <table> GROUP BY GROUPING SETS
((col1,col2), (col2,col3), (col2), ());
GROUP BY (col1, col2)
GROUP BY (col2, col3)
GROUP BY col2
GROUP BY ()
The result of the previous SELECT is equivalent to the result of doing a UNION ALL for the four selects aggregating at the four group levels. So a rollup() or cube() operation can be translated into a grouping sets specification.
<grouping-set-list> can itself
be a <grouping-set-list>, and so can also be a cube() or rollup(). Any such complex
specified grouping-set-list can always be expanded into a grouping-set-list,
as in the following example:GROUPING SETS (ROLLUP(col1,col2), CUBE(col1,col2))
GROUPING SETS ((col1,col2), (col1), (), (col1,col2), (col1), (col2),
())
DISTINCT GROUPING SETS (ROLLUP(col1,col2), CUBE(col1,col2))
GROUPING SETS ((col1,col2), (col1), (col2), ())
Also, the grouping set (col1, col2) is equivalent to (col2, col1), so the elimination of duplicates in the grouping-set-list is done by putting list entries into a canonical form that lists unique entries in the order in which they occur in the grouping sets clause.
GROUP BY GROUPING SETS ((A), (B)), GROUPING SETS ((X, Y), (Z))
GROUP BY GROUPING SETS ((A, X, Y), (A, Z), (B, X, Y), (B, Z))
GROUP BY A, GROUPING SETS ((X,Y), (Z))
GROUP BY GROUPING SETS ((A, X, Y), (A, Z))
STATE | CITY | SUM
_____________________________
CA | Los Angeles | 600
CA | San Diego | 225
CA | San Francisco | 450
CA | | 1275
MA | Boston | 460
MA | Springfield | 345
MA | | 805
| | 2080
STATE | CITY | SUM | GROUPING(city)
_____________________________________________
CA | Los Angeles | 600 | 0
CA | San Diego | 225 | 0
CA | San Francisco | 450 | 0
CA | | 1275 | 1
MA | Boston | 460 | 0
MA | Springfield | 345 | 0
MA | | 805 | 1
| | 2080 | 1
STATE | CITY | SUM | GROUPING(city) | GROUPING(state)
________________________________________________________________
CA | Los Angeles | 600 | 0 | 0
CA | San Diego | 225 | 0 | 0
CA | San Francisco | 450 | 0 | 0
CA | | 1275 | 1 | 0
MA | Boston | 460 | 0 | 0
MA | Springfield | 345 | 0 | 0
MA | | 805 | 1 | 0
| | 2080 | 1 | 1