1、cube:生成多维数据集，包含各维度可能组合的交叉表格，使用with 关键字连接 with cube

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([店名]) != 1AND 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 ##PudianCardGROUP BY [档案号], [店名], [店长], [系列]WITH cubeHAVING GROUPING([店名]) != 1 AND GROUPING([店长]) != 1 ) AS W )UNIONALL (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
[店名]

tags: GROUPING,AS,店名,CASE,THEN,WHEN,END,ELSE,店长,档案,cube,SELECT,FROM,系列,合计

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。