Sometimes when we use the SQL GROUP BY
clause to group queries, it would be nice to have totals and subtotals included in the query results.
For example, if our query returns cities and their populations, grouped by the city’s district and perhaps also grouped by country, it would be nice to include subtotals for each district (based on the aggregate populations of all cities in the district). And it might also be nice to have the total population of each country, based on the same aggregate data.
Another way of putting it is that we want to get a summary of the summary. Or an aggregate of the aggregate. This is sometimes referred to as “super aggregate”.
Fortunately, in MySQL we can use the WITH ROLLUP
modifier of the GROUP BY
clause to achieve exactly that.