使用分组集-标识级别名称并消除某些集

时间:2019-03-28 20:44:56

标签: sql sql-server

如果我有一个具有以下结构的表:

  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)
)

关于使用分组集,我有两个问题:

  1. 如果不希望将特定集合分组,如何消除该集合。
  2. 如何添加级别名称,商店,区域,StoreRegion等?

我尝试使用grouping_id,但这不是万无一失的。所以想知道是否还有其他方法。

0 个答案:

没有答案