The use of the GROUPING SETS extension in the GROUP BY clause provides a means to produce one result set that's the concatenation of multiple results sets based on different groupings. In other words, a UNION ALL operation is performed combining the result sets of multiple groupings into one result set.
A UNION ALL operation, and therefore the GROUPING SETS extension, doesn't eliminate duplicate rows from the result sets that are being combined.
Syntax
The syntax for a single GROUPING SETS extension is:
A GROUPING SETS extension can contain any combination of one or more comma-separated expressions, lists of expressions enclosed in parentheses, ROLLUP extensions, and CUBE extensions.
The GROUPING SETS extension is specified in the context of the GROUP BY clause:
The items specified in select_list must also either:
Appear in the GROUPING SETS expression_list
Be aggregate functions such as COUNT, SUM, AVG, MIN, or MAX
Be constants or functions whose return values are independent of the individual rows in the group (for example, the SYSDATE function)
Use the GROUP BY clause to specify multiple GROUPING SETS extensions as well as multiple occurrences of other GROUP BY extensions and individual expressions.
Use the ORDER BY clause to display the output in a meaningful structure and to guarantee the order of the result set.
Examples
The following query produces a union of groups given by columns loc, dname, and job:
The result is as follows:
This is equivalent to the following query, which uses the UNION ALL operator:
The output from the UNION ALL query is the same as the GROUPING SETS output:
This example shows how you can use various types of GROUP BY extensions together in a GROUPING SETS expression list:
The following is the output from this query:
The output is basically a concatenation of the result sets from GROUP BY loc, GROUP BY ROLLUP (dname, job), and GROUP BY CUBE (job, loc). These individual queries are:
The result set from the GROUP BY loc clause is:
The following query uses the GROUP BY ROLLUP (dname, job) clause:
The result set from the GROUP BY ROLLUP (dname, job) clause is:
The following query uses the GROUP BY CUBE (job, loc) clause:
The result set from the GROUP BY CUBE (job, loc) clause is:
If the previous three queries are combined with the UNION ALL operator, a concatenation of the three results sets is produced:
The output is the same as when the GROUP BY GROUPING SETS (loc, ROLLUP (dname, job), CUBE (job, loc)) clause is used.