The ROLLUP function is a powerful tool in SQL that allows you to generate subtotals and grand totals in aggregated queries. This feature is particularly useful for reports and analysis, where there is a need to calculate consolidated values at different levels of detail.
The ROLLUP function is used in conjunction with the GROUP BY clause to create hierarchical groupings. It automatically adds extra rows that represent subtotals (partial sums) and the grand total at the end of the query.
SELECT column1, column2, aggregation(column3) FROM table GROUP BY ROLLUP(column1, column2);
Let's work with the products table created in the code above, which contains information about products and their categories.
If we query only the grouping by category, we get the following result:
SELECT product_category, SUM(product_value) AS total FROM products GROUP BY product_category;
Result:
Category | Total |
---|---|
clothing | 40.48 |
food | 6.97 |
By adding the ROLLUP function, we include the subtotals and the grand total:
SELECT CASE WHEN product_category IS NULL THEN 'Grand Total' ELSE product_category END AS category, SUM(product_value) AS total FROM products GROUP BY ROLLUP(product_category);
Result:
Category | Total | ||||||||
---|---|---|---|---|---|---|---|---|---|
clothing | 40.48 | ||||||||
food | 6.97 | ||||||||
|
47.45 |
We can go further and calculate subtotals at multiple levels. For example, to calculate subtotals by category and product:
SELECT CASE WHEN product_category IS NULL AND product_name IS NULL THEN 'Grand Total' WHEN product_name IS NULL THEN 'Subtotal - ' || product_category ELSE product_name END AS description, SUM(product_value) AS total FROM products GROUP BY ROLLUP(product_category, product_name);
Result:
Description | Total |
---|---|
T-shirt | 10.99 |
Shorts | 8.99 |
Shoes | 20.50 |
Subtotal - clothing | 40.48 |
Rice | 1.99 |
Popcorn | 0.99 |
Filet Steak | 3.99 |
Subtotal - food | 6.97 |
Grand Total | 47.45 |
Description | Total |
---|---|
T-shirt | 10.99 |
Shorts | 8.99 |
Shoes | 20.50 |
Subtotal - clothing | 40.48 |
Rice | 1.99 |
Popcorn | 0.99 |
Filet Steak | 3.99 |
Subtotal - food | 6.97 |
Grand Total | 47.45 |
The ROLLUP function simplifies the creation of complex reports, reducing the need for manual manipulation. This functionality is supported by many databases such as Oracle, SQL Server, and MySQL. Use it to make your queries more efficient and your reports more dynamic! ?
The above is the detailed content of ROLLUP. For more information, please follow other related articles on the PHP Chinese website!