Instruction
Good job! As you saw, using UNION ALL is one way of dealing with such reports, but it seems to cause all kinds of problems:
- The statement becomes huge as more queries are added with
UNION ALL - The table has to be accessed multiple times, which affects performance
- Adding
NULLvalues in theSELECTclause is awkward and error prone
That's where GROUPING SETS come in handy. They allow you to perform multiple groupings within a single query; each grouping is explicitly stated, as we see below:
SELECT date_received, customer_id, repair_center, AVG(repair_duration) AS avg_repair_duration FROM warranty_repair GROUP BY GROUPING SETS ( (customer_id, repair_center), (date_received) )
As you can see, GROUP BY GROUPING SETS is followed by a pair of parentheses. Inside, we put all the grouping combinations we wish to get, each in a separate pair of parentheses and separated by a comma.
Exercise
Run the template query. Note how two different grouping levels are created.



