如果我有一个具有以下结构的表:
StoreID StoreName Region Dept Sales month
1 xyz East Phones 1000 201902
2 pch west movies 3000 201902
3 cts west tech 500 201902
4 xyz east cars 8000 201902
我们可以编写分组集合来轻松地做到这一点,而不是编写单独的联合所有查询以汇总每个级别的数据。尤其是如果表中的列数很大并且我们必须编写多个分组依据。
与工会一起-我愿意:
select month,'Store' as Level,'N/A' as store 'N/A' as Region,'N/A' as dept, sum(sales)
from stores
group by month
union all
select month,'Region' as Level,'N/A' as store,region as Region,'N/A' as dept, sum(sales)
from stores
group by month,region
union all
select month,'StoreRegion' as Level,store as store,region as Region,'N/A' as dept, sum(sales)
from stores
group by month,store,region
等
在分组集中可以这样写:
select month,store,region,dept,sum(sales)
from stores
group by grouping sets (
(month,store,region,dept)
,(month,store)
,(month,store,region)
)
关于使用分组集,我有两个问题:
我尝试使用grouping_id,但这不是万无一失的。所以想知道是否还有其他方法。