grouping set
时间: 2023-11-06 10:07:53 浏览: 42
Grouping sets is a SQL operation that allows grouping data by multiple columns or expressions, and returning aggregates for each group. It provides a way to specify multiple grouping sets, where each set can be a single column or a combination of columns, and aggregates are computed for each set.
For example, consider a table of sales data with columns like region, product, year, and month. We can use grouping sets to generate different levels of aggregates based on these columns. For instance, we can group by region and year, or by product and month, or by region, product, and year.
To use grouping sets, we can use the GROUP BY clause followed by the GROUPING SETS keyword, and then a list of grouping sets enclosed in parentheses. Each set can be specified as a comma-separated list of columns or expressions.
Here's an example query that shows total sales by region, product, and year:
```
SELECT region, product, year, SUM(sales) AS total_sales
FROM sales
GROUP BY GROUPING SETS ((region), (product, year), (region, product, year));
```
This query will return three sets of aggregates: total sales by region, total sales by product and year, and total sales by region, product, and year.
阅读全文