1

在 MsSQL 2008 中,我试图在其末尾显示 3 个不同列的总和。

目前我的查询返回在此处输入图像描述

这是由 (@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 的总和。我试过使用汇总,但这并没有给我正确的结果。可能只是做错了,但是选择语句必须是什么样子才能得到我需要的东西?

4

2 回答 2

3

有两种方法可以做到这一点。第一种是旧的 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 的结果

GROUPING SETS EquivalentsUsing GROUP BY with ROLLUP、CUBE 和 GROUPING SETS是另外两个来源,其中包含有关使用的良好信息GROUPING SETS

于 2013-02-18T19:03:54.530 回答
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、02 和总计之外的所有列中为 NULL 的行。

于 2013-02-18T18:35:16.733 回答