SQL Pivot查询结束时的列总计

时间:2013-12-18 06:30:42

标签: sql sql-server-2008 pivot

我已经生成了以下SQL Server 2008数据透视表,它给了我渴望的结果。 我想在枢轴末端添加总列,我发现它很难。

请找到我用于数据透视的SQL

Select * from (
     Select Case when (podocstatus = 'CL') then 'Closed PO'
         when (podocstatus = 'OP') then 'Open PO'
         when (podocstatus = 'SC') then 'Short Closed PO'   
    end as POStatus, 
    YEAR(podate) as [Year], YEAR(podate) as [poyear] , LEFT (datename(Month,podate),3) as [pomonth]
    From PO_order_hdr
    Where podocstatus IN ('SC','CL','OP')
    ) as POnumber
PIVOT
(
    Count(poyear)
    FOR [pomonth]  IN (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)

)as PVT

请帮忙。

1 个答案:

答案 0 :(得分:15)

最简单的解决方案是简单地做这样的事情:

Select *,
    Jan + Feb + Mar + Apr + May + Jun + Jul + Aug + Sep + Oct + Nov + Dec AS [Total]
from
    ...

一般情况的替代解决方案是使用子选择。将内部查询移动到CTE中,使事情更容易使用:

WITH POnumber (POStatus, [Year], [poyear], [pomonth]) AS
(
    Select sase when (podocstatus = 'CL') then 'Closed PO'
         when (podocstatus = 'OP') then 'Open PO'
         when (podocstatus = 'SC') then 'Short Closed PO'   
    end as POStatus, 
    YEAR(podate) as [Year], YEAR(podate) as [poyear] , LEFT (datename(Month,podate),3) as [pomonth]
    From PO_order_hdr
    Where podocstatus IN ('SC','CL','OP')
)
select *,
    -- Subselect that counts the total for the given status and year:
    (select count([Year]) from POnumber T 
     where T.POStatus = PVT.POStatus and T.poyear = PVT.poyear) as [Total]
from POnumber
PIVOT
(
    Count(poyear)
    FOR [pomonth]  IN (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)
)as PVT