SQLserver中cube:多维数据集实例详解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
'合计'
sql存储过程实例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:多维数据集实例详解的全部内容,希望对⼤家有所帮助。感兴趣的朋友可以继续参阅:、、等,有什么问题可以随时留
⾔,⼩编会及时回复⼤家的。感谢各位对本站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。