Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
GROUPING SETS
Summary

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:

  1. The statement becomes huge as more queries are added with UNION ALL
  2. The table has to be accessed multiple times, which affects performance
  3. Adding NULL values in the SELECT clause 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.