简体   繁体   中英

SQL Server Pivot Row Total

I'm using SQL Server 2012 and have the below pivot code that works fine. However, how do I include a row total ie a sum of the recorded amount for each account over the course of the year?

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

Any help would be greatly appreciated.

If anyone is interested this is the final working solution:

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

this would also work for you and might perform better

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]

works the same as pivot but gives a little more control when including extra information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM