在mssql 2008中显示列末尾的列总和

时间:2013-02-18 18:30:56

标签: sql-server-2008 dynamic-sql rollup

在MsSQL 2008中,我试图在最后显示3个不同列的总和。

目前我的查询返回enter image description here

选择(@grouping = maingroup,subgroup,subsubgroup,season,vendorid,[01] as'01',[02] as'02',Total)

set @sql = 'select '+@grouping+' from ##aa'
execute sp_executesql @sql

我需要在各自列的末尾加上01,02和Total的总和。我曾尝试使用汇总,但这并没有给我正确的结果。可能只是做错了,但是选择语句必须看起来像我需要什么?

2 个答案:

答案 0 :(得分:3)

有两种方法可以做到这一点。第一个是旧的pre sql-server-2008方法,这样做是使用UNION ALL,第一个SELECT返回表中的原始数据,第二个返回SUMS的01,02和总字段:

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), ())

两者都应该返回:

Results of GROUPING SETS

GROUPING SETS EquivalentsUsing GROUP BY with ROLLUP, CUBE, and GROUPING SETS是另外两个来源,提供有关使用GROUPING SETS

的详细信息

答案 1 :(得分:0)

Select maingroup, subgroup, subsubgroup, season, vendorid, sum([01]) as '01', sum([02]) as '02', sum(Total)
FROM ##aa
Group by grouping sets ((maingroup, subgroup, subsubgroup, season, vendorid),())

最后一个条目将是除01,202和total之外的所有列中的NULL行。