【问题标题】:Column Total at the end of SQL Pivot querySQL Pivot 查询末尾的列总计
【发布时间】:2014-01-06 05:10:48
【问题描述】:

我已经生成了以下 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

请帮忙。

【问题讨论】:

  • 您想要的结果现在显示为 postatus,year,jan,feb...,dec 对吗?你想怎么得到结果?
  • LEFT (datename(Month,podate),3)永远生成Sept的值。
  • 你好 Magesh 和 Damein_the_unbeliever,@magesh,你是对的,它显示了 POstatus、年份、Jan、Feb、Mar....Dec,我希望在 DEC 之后为每个状态行提供总计,这将在下面列出。 damein_the_unbeliever - 是的,我用 SEPT 代替了 SEP,这是拼写错误,感谢您的关注。
  • Select *,(PVT.Jan + .... + PVT.Dec) as Total 可以给你预期的结果...
  • 你好朋友谢谢你的帮助..我最后得到了总数..我在 TOTAL 列之后寻找新的 4 列..即第 1 季度,第 2 季度...第 3 季度 ..第 4 季度 ..现在如何总和 - Jan+Feb+Mar/3.. Apr+May+June/3 ?

标签: sql sql-server-2008 pivot


【解决方案1】:

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

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

【讨论】:

  • 谢谢丹,最简单的解决方案已经成功了。小细节起着重要的作用...非常感谢您的友好建议和帮助。实际上我是 SQL 新手,但通过诸如 stackoverflow 之类的有用网站和像你这样的好心人自学。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
相关资源
最近更新 更多