有两种方法可以做到这一点。第一种是旧的 sql-server-2008 之前的方法是使用 a UNION ALL
,第一个SELECT
返回表中的原始数据,第二个返回 01、02 和 Total 字段的 SUMS:
SELECT maingroup,
subgroup,
subsubgroup,
season,
vendorid,
[01] AS '01',
[02] AS '02',
Total AS Total
FROM #aa
UNION ALL
SELECT null as maingroup,
null as subgroup,
null as subsubgroup,
null as season,
null as vendorid,
sum([01]) AS '01',
sum([02]) AS '02',
sum(Total) AS Total
FROM #aa
在 sql-server-2008 及更高版本中,您可以使用它来代替使用GROUPING SETS
。上面使用的等效查询GROUPING SETS
是:
SELECT maingroup,
subgroup,
subsubgroup,
season,
vendorid,
sum([01]) AS '01',
sum([02]) AS '02',
sum(Total) AS Total
FROM #aa
GROUP BY GROUPING SETS((maingroup, subgroup, subsubgroup, season, vendorid), ())
两者都应该返回:
GROUPING SETS Equivalents和Using GROUP BY with ROLLUP、CUBE 和 GROUPING SETS是另外两个来源,其中包含有关使用的良好信息GROUPING SETS