Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Pivot查询末尾的列总数_Sql_Sql Server 2008_Pivot - Fatal编程技术网

SQL Pivot查询末尾的列总数

SQL Pivot查询末尾的列总数,sql,sql-server-2008,pivot,Sql,Sql Server 2008,Pivot,我已经生成了以下SQLServer2008Pivot,它给出了我想要的结果。 我想在pivot的末尾添加total列,我发现这很困难 请查找我用于pivot的SQL Select * from ( Select Case when (podocstatus = 'CL') then 'Closed PO' when (podocstatus = 'OP') then 'Open PO' when (podocstatus = 'SC') then '

我已经生成了以下SQLServer2008Pivot,它给出了我想要的结果。 我想在pivot的末尾添加total列,我发现这很困难

请查找我用于pivot的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

请提供帮助。

最简单的解决方案是简单地执行以下操作:

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

您期望的结果现在显示为postatus、year、jan、feb…、dec,对吗?如何获得结果?
LEFT(datename(Month,podate),3)
将永远不会生成
Sept
的值。您好,Magesh和Damein_,不信者,@Magesh,因为您是对的,它显示了POstatus,year,Jan,Feb,Mar……Dec,我想要下面列出的每个stautus行在12月后的总计。damein_不信者-是的,我把SEP改成了SEP,这是打字错误,感谢大家的关注。选择*,(PVT.Jan+…+PVT.Dec)作为总数可以给你你你期望的结果…你好,朋友们,谢谢你的帮助。。我最后得到了总数。。我正在寻找总计列之后的新4列。。那是第1季度,第2季度,第3季度,第4季度。。现在如何求和-一月+二月+三月/3。。4月+5月+6月/3日?谢谢Dan,最简单的解决方案成功了。。小细节扮演着巨大的角色。。。非常感谢你的忠告和帮助。事实上,我是SQL新手,但通过stackoverflow等有用的网站和像你这样善良的人进行自学。