How to use the ROLLUP operator?
To use the ROLLUP operator, you need to add it after the GROUP BY clause, and list the columns that you want to group by. The order of the columns matters, as it determines the hierarchy of the subtotals. The rightmost column will have the most detailed level of aggregation, and the leftmost column will have the least detailed level of aggregation. For example, the following query will group the sales data by region, country, and product, and calculate the sum of sales for each level:
SELECT region, country, product, SUM(sales) AS total_sales
FROM sales_table
GROUP BY ROLLUP (region, country, product);
The result of this query will look something like this:
| region | country | product | total_sales |
|--------|---------|---------|-------------|
| Asia | China | A | 100 |
| Asia | China | B | 200 |
| Asia | China | NULL | 300 |
| Asia | India | A | 150 |
| Asia | India | B | 250 |
| Asia | India | NULL | 400 |
| Asia | NULL | NULL | 700 |
| Europe | France | A | 120 |
| Europe | France | B | 220 |
| Europe | France | NULL | 340 |
| Europe | Germany | A | 130 |
| Europe | Germany | B | 230 |
| Europe | Germany | NULL | 360 |
| Europe | NULL | NULL | 700 |
| NULL | NULL | NULL | 1400 |
As you can see, the ROLLUP operator adds rows with NULL values to indicate the subtotals. The NULL value in the product column means the subtotal for each country, the NULL value in the country column means the subtotal for each region, and the NULL value in the region column means the grand total for all the data.