SQL:多维数据集Cube
2020-04-28 16:18 huoit 阅读(768) 评论(0) 收藏 举报
Cude实际就是group by的组和加上合计 生成一个多维的数据集
示例:
--初始化 if not object_id(N'Tempdb..#Temp') is null drop table #T Go Create table #Temp([Item] nvarchar(22),[Color] nvarchar(22),[Quantity] int) Insert #Temp select N'桌子',N'白色',1 union all select N'桌子',N'红色',2 union all select N'椅子',N'白色',3 union all select N'椅子',N'红色',4 --1.常规的写法,统计各个维度的数据如下: --根据类别 select Item,'ALL' as 'Color',sum(Quantity) from #Temp group by Item union --根据颜色 select 'ALL' as 'Item',Color,sum(Quantity) from #Temp group by Color union --颜色+类别 select Item,Color,sum(Quantity) from #Temp group by Item,Color union --所有合计 select 'ALL' as 'Item','ALL' as 'Color',sum(Quantity) from #Temp --2.使用cube --cube会根据group by 的所有列进行计算包括合计,这里的NULL值就是代表的ALL select Item,Color ,sum(Quantity) as 'Count' from #Temp group by Item,Color with cube --如果事实表#Temp里有NULL怎么区分Cube里的NULL,使用grouping(列名),如果来源于事实表则返回0,否则返回1 select case when grouping(Item)=1 then 'ALL' else isnull(Item,'空数据') end as 'Item', case when grouping(Color)=1 then 'ALL' else isnull(Color,'空数据') end as 'Color', sum(Quantity) as 'Count' from #Temp group by Item,Color with cube
1、如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
2、欢迎各位转载,但是未经作者本人同意,转载文章请在文章页面明显位置标明作者和原文连接,否则保留追究法律责任的权利。
作者博客: http://www.cnblogs.com/xmai/
浙公网安备 33010602011771号