SQLserver中cube:多维数据集实例详解
程序员文章站
2022-03-17 13:09:17
1、cube:生成多维数据集,包含各维度可能组合的交叉表格,使用with 关键字连接 with cube
根据需要使用union all 拼接
判断 某一列的n...
1、cube:生成多维数据集,包含各维度可能组合的交叉表格,使用with 关键字连接 with cube
根据需要使用union all 拼接
判断 某一列的null值来自源数据还是 cube 使用grouping关键字
grouping([档案号]) = 1 : null值来自cube(代表所有的档案号)
grouping([档案号]) = 0 : null值来自源数据
举例:
select * into ##get from (select * from ( select case when (grouping([档案号]) = 1) then '合计' else [档案号] end as '档案号', case when (grouping([系列]) = 1) then '合计' else [系列] end as '系列', case when (grouping([店长]) = 1) then '合计' else [店长] end as '店长', sum (剩余次数) as '总剩余', case when (grouping([店名]) = 1) then '合计' else [店名] end as '店名' from ##pudiancard group by [档案号], [店名], [店长], [系列] with cube having grouping([店名]) != 1 and grouping([档案号]) = 1 --and grouping([系列]) = 1 ) as m union all (select * from ( select case when (grouping([档案号]) = 1) then '合计' else [档案号] end as '档案号', case when (grouping([系列]) = 1) then '合计' else [系列] end as '系列', case when (grouping([店长]) = 1) then '合计' else [店长] end as '店长', sum (剩余次数) as '总剩余', case when (grouping([店名]) = 1) then '合计' else [店名] end as '店名' from ##pudiancard group by [档案号], [店名], [店长], [系列] with cube having grouping([店名]) != 1 and grouping([店长]) != 1 ) as p ) union all (select * from ( select case when (grouping([档案号]) = 1) then '合计' else [档案号] end as '档案号', case when (grouping([系列]) = 1) then '合计' else [系列] end as '系列', case when (grouping([店长]) = 1) then '合计' else [店长] end as '店长', sum (剩余次数) as '总剩余', case when (grouping([店名]) = 1) then '合计' else [店名] end as '店名' from ##pudiancard group by [档案号], [店名], [店长], [系列] with cube having grouping([店名]) != 1 and grouping([店长]) != 1 ) as w ) union all (select * from ( select case when (grouping([档案号]) = 1) then '合计' else [档案号] end as '档案号', case when (grouping([系列]) = 1) then '合计' else [系列] end as '系列', case when (grouping([店长]) = 1) then '合计' else [店长] end as '店长', sum (剩余次数) as '总剩余', case when (grouping([店名]) = 1) then '合计' else [店名] end as '店名' from ##pudiancard group by [档案号], [店名], [店长], [系列] with cube having grouping([店名]) = 1 and grouping([店长]) = 1 and grouping([档案号]) = 1 ) as k ) ) as t
2、rollup:功能跟cube相似
3、将某一列的数据作为列名,动态加载,使用存储过程,拼接字符串
declare @st nvarchar (max) = '';select @st =@st + 'max(case when [系列]=''' + cast ([系列] as varchar) + ''' then [总剩余] else null end ) as [' + cast ([系列] as varchar) + '],' from ##get group by [系列]; print @st;
4、根据某一列分组,分别建表
select 'select row_number() over(order by [卡项] desc) as [序号], [会员],[档案号],[卡项],[剩余次数],[员工],[店名] into ' + ltrim([店名]) + ' from 查询 where [店名]=''' + [店名] + ''' order by [卡项] desc' from 查询 group by [店名]
总结
以上就是本文关于sqlserver中cube:多维数据集实例详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅:mysql子查询和嵌套查询优化实例解析、几个比较重要的mysql变量、oracle sql语句优化技术要点解析等,有什么问题可以随时留言,小编会及时回复大家的。感谢各位对本站的支持!