SQL Server Pivot Row Total

时间:2016-11-10 16:47:48

标签: sql sql-server pivot

我正在使用SQL Server 2012,并且具有以下枢轴代码,可以正常工作。但是,如何在一年中包括行总数,即每个帐户的记录金额总和?

SELECT *
FROM (
SELECT [Account],[AccountDesc], CONVERT(CHAR(4), AccDate, 100) as [Month], [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE [Employee] = @Employee
) AS s
PIVOT
(
SUM ([RecordedAmount])
FOR [Month] in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec)
) As pvt

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

如果有人有兴趣,这是最终的解决方案:

SELECT pvt.* ,Isnull(pvt.jan,0) +Isnull(pvt.feb,0) +Isnull(pvt.mar,0) +Isnull(pvt.apr,0) +Isnull(pvt.may,0) +Isnull(pvt.jun,0) +Isnull(pvt.jul,0) +Isnull(pvt.aug,0) +Isnull(pvt.sept,0) +Isnull(pvt.oct,0) +Isnull(pvt.nov,0) as YearTotal
FROM (
SELECT [Account],[AccountDesc], CONVERT(CHAR(4), AccDate, 100) as [Month], [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE [Employee] = @Employee
) AS s
pivot (
SUM ([RecordedAmount])
FOR [Month] in (May, Jun, Jul, Aug, Sept, Oct, Nov, Dec, Jan, Feb, Mar, Apr)
) As pvt

答案 1 :(得分:0)

这对你也有用,可能会有更好的表现

SELECT  [Account],
        [AccountDesc],
        SUM(CASE WHEN [Month] = 'Jan' THEN [RecordedAmount] END) AS [Jan],
        SUM(CASE WHEN [Month] = 'Feb' THEN [RecordedAmount] END) AS [Feb],
        SUM(CASE WHEN [Month] = 'Mar' THEN [RecordedAmount] END) AS [Mar],
        SUM(CASE WHEN [Month] = 'Apr' THEN [RecordedAmount] END) AS [Apr],
        SUM(CASE WHEN [Month] = 'May' THEN [RecordedAmount] END) AS [May],
        SUM(CASE WHEN [Month] = 'Jun' THEN [RecordedAmount] END) AS [Jun],
        SUM(CASE WHEN [Month] = 'Jul' THEN [RecordedAmount] END) AS [Jul],
        SUM(CASE WHEN [Month] = 'Aug' THEN [RecordedAmount] END) AS [Aug],
        SUM(CASE WHEN [Month] = 'Sept' THEN [RecordedAmount] END) AS [Sept],
        SUM(CASE WHEN [Month] = 'Oct' THEN [RecordedAmount] END) AS [Oct],
        SUM(CASE WHEN [Month] = 'Nov' THEN [RecordedAmount] END) AS [Nov],
        SUM(CASE WHEN [Month] = 'Dec' THEN [RecordedAmount] END) AS [Dec],
        SUM([RecordedAmount]) AS [Total]
FROM    (
            SELECT  [Account],
                    [AccountDesc],
                    CONVERT(CHAR(4),AccDate,100) AS [Month],
                    [RecordedAmount]
            FROM    [tblGLS215_2016_2017]
            WHERE   [Employee] = @Employee 
        ) t
GROUP BY [Account],
        [AccountDesc]

与枢轴相同,但在包含额外信息时可以提供更多控制。