使用汇总(或行总计)进行 SQL 透视
Posted
技术标签:
【中文标题】使用汇总(或行总计)进行 SQL 透视【英文标题】:SQL Pivoting With rollup (or a row totals) 【发布时间】:2016-10-28 19:41:30 【问题描述】:我对一些总帐科目和按月计算的总和有以下查询:
Select Month, [41100],[42000],[45100],[42200],[42300],[42400],[45200],
[45205]
from ( Select ACC_0 , (CONVERT(NUMERIC(12,2),(AMTLED_0))) as Amount , MONTH(ACCDAT_0) as Month
from x3v6.CICPROD.GACCENTRYD with(nolock)
where YEAR(ACCDAT_0) = YEAR(GETDATE())
) as s1
PIVOT (SUM(Amount) FOR ACC_0 IN ([41100],[42000],[45100],[42200],[42300],[42400],[45200],
[45205])) as pivot1
这会产生以下结果集:
Month 41100 42000 45100 42200 42300 42400 45200 45205
1 3857806.91 19987.61 49876.84 49078.59 2173.63 NULL 375.00 68.52
2 4459775.79 5145.69 64442.41 58102.00 2684.40 NULL 230.00 NULL
3 4311142.03 8594.31 44220.72 33850.08 3116.75 141.00 1917.50 NULL
4 4413788.57 5613.67 58038.20 55359.25 4398.67 NULL 4796.38 132.00
5 4251083.15 4372.07 48488.03 53592.00 2869.86 127.00 110.00 128.00
6 4353075.16 9705.83 53925.37 64104.00 2304.65 2822.78 153.41 NULL
7 4549485.41 10054.92 61607.99 65136.00 1531.66 186.30 265.50 NULL
8 4239075.39 16917.10 43012.02 51591.25 1538.01 1690.91 350.00 NULL
9 4331439.41 39248.15 56368.41 74928.00 1858.82 694.32 160.00 66.00
10 3673909.02 12283.42 38928.66 28608.00 NULL NULL 120.00 NULL
我想在右侧的一列中按每一行获得一个 TOTAL 计数。我将如何使用 PIVOT 语法完成此操作?我尝试使用分组集,但它对我不起作用。
版本是 SQL Server 2012。
谢谢
【问题讨论】:
【参考方案1】:一种简单的方法是不使用 PIVOT,而是将 SUM 聚合与 CASE 表达式一起使用。
SELECT Month,
SUM(CASE WHEN ACC_0 = '41100' THEN Amount END) AS [41100],
SUM(CASE WHEN ACC_0 = '42000' THEN Amount END) AS [42000],
SUM(CASE WHEN ACC_0 = '45100' THEN Amount END) AS [45100],
SUM(CASE WHEN ACC_0 = '42200' THEN Amount END) AS [42200],
SUM(CASE WHEN ACC_0 = '42300' THEN Amount END) AS [42300],
SUM(CASE WHEN ACC_0 = '42400' THEN Amount END) AS [42400],
SUM(CASE WHEN ACC_0 = '45200' THEN Amount END) AS [45200],
SUM(CASE WHEN ACC_0 = '45205' THEN Amount END) AS [45205],
SUM(Amount) AS [Total]
FROM (SELECT ACC_0,
(CONVERT(NUMERIC(12,2),(AMTLED_0))) AS Amount,
MONTH(ACCDAT_0) AS Month
FROM x3v6.CICPROD.GACCENTRYD WITH (NOLOCK)
WHERE YEAR(ACCDAT_0) = YEAR(GETDATE())
-- only get the ACC_0 values you need so Total is correct
AND ACC_0 IN ('41100','42000','45100','42200','42300','42400','45200','45205')
) AS s1
GROUP BY Month
【讨论】:
以上是关于使用汇总(或行总计)进行 SQL 透视的主要内容,如果未能解决你的问题,请参考以下文章