SQL Pivoting使用汇总(或行总计)

时间:2016-10-28 19:41:31

标签: sql-server-2012 pivot

我有一些g / l帐户的查询和按月计算的总和:

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

我想通过右边一列中的每个ROW获得一个TOTAL总计。我将如何使用PIVOT语法实现此目的?我尝试使用分组集,但它对我不起作用。

版本是SQL Server 2012。

由于

1 个答案:

答案 0 :(得分:0)

一种简单的方法是不使用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