In this tutorial we explore the SELECT command's GROUP BY clause as well as its related extensions GROUPING SETS, ROLLUP, and CUBE.
Basic GROUP BY queries are not too hard to understand. Many readers will have already written simple ones themselves. When I first studied the ROLLUP and CUBE extensions however I found it hard to wrap my head around them. It was not until I studied GROUPING SETS that things started to fall into place. If I had to do it all over again I would have studied GROUPING SETS first and then learnt ROLLUP and CUBE. This is the order we will follow in this tutorial.
(Note that GROUPING SETS support was added to databases like Oracle and SQL Server after ROLLUP and CUBE were introduced. This may explain why documentation such as Chapter 20, SQL for Aggregation in Data Warehouses, of the Oracle® Database Data Warehousing Guide or the Using GROUP BY with ROLLUP, CUBE, and GROUPING SETS chapter of the SQL Server 2008 product documentation choose to explain GROUPING SETS after ROLLUP and CUBE.)