rollup is an aggregate function in SQL that is used to perform multi-level grouping and summary of data in a hierarchical structure. Its syntax is: rollup(expression). By aggregating data at different granularities, the rollup function can easily create multi-level aggregations, improve query performance, and allow users to explore data at different granularities.
Usage of rollup in SQL
What is rollup?
rollup is an aggregate function in SQL that is used to group and summarize data in a hierarchy. It allows users to perform multi-level aggregation of data, from the most detailed level to the most summary level.
How to use rollup?
The syntax of the rollup function is as follows:
rollup(expression)
Among them:
Usage example of rollup function:
Example 1: Summarize sales by "region" and "product" groups
SELECT region, product, SUM(sales) FROM sales_table GROUP BY ROLLUP(region, product);
This query will generate the following output:
region | product | sum(sales) |
---|---|---|
Central | Product A | 1000 |
Product B | 1500 | |
Total | 2500 | |
Product A | 500 | |
Product B | 750 | |
Total | 1250 | |
Product A | 700 | |
Product B | 900 | |
Total | 1600 | |
5350 |
Easily create multi-level aggregations. The above is the detailed content of How to use rollup in sql. For more information, please follow other related articles on the PHP Chinese website!SELECT year, quarter, month, COUNT(order_id)
FROM orders_table
GROUP BY ROLLUP(year, quarter, month);
year
##2021
quarter
month count(order_id)
1
1 100
2021 1
2 150
2021 1
Total 250
2021 2
3 120
2021 2
4 130
2021 2
Total 250
2022 1
1 90
2022 1
Total 90
Grand Total ## Advantages of rollup:
630