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:
<code class="sql">rollup(expression)</code>
Among them:
Usage example of rollup function:
Example 1: Summarize sales by "region" and "product" groups
<code class="sql">SELECT region, product, SUM(sales) FROM sales_table GROUP BY ROLLUP(region, product);</code>
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 |
<code class="sql">SELECT year, quarter, month, COUNT(order_id)
FROM orders_table
GROUP BY ROLLUP(year, quarter, month);</code>
This query will generate the following output:
quarter | month | count(order_id) | |
---|---|---|---|
1 | 100 | 2021 | |
2 | 150 | 2021 | |
Total | 250 | 2021 | |
3 | 120 | 2021 | |
4 | 130 | 2021 | |
Total | 250 | 2022 | |
1 | 90 | 2022 | |
Total | 90 | Grand Total | |
630 |
Easily create multi-level aggregations.
Allows users to explore data at different granularities.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!