具有多个结果值的PIvot

时间:2017-02-21 20:08:05

标签: sql-server sql-server-2008 pivot pivot-table

我试图在此数据透视表中添加多个总和,但我还没有成功,

这是原始数据 来自

select 
    billname, 
    orderperiodyear,
    Sum_buyprice,
    Sum_Sellprice,
    Tonnage 
From Sum_Orders

enter image description here

这是我的支点如何在支点结果中包含购买价格和吨位

SELECT billname,SUM([2017])AS '2017', SUM([2016]) AS '2016'
FROM   Sum_Orders
PIVOT
    (
       SUM(Sum_SellPrice)
            FOR OrderperiodYear IN ([2017],[2016])
     )AS pvt
WHERE  OrderStatus IN ('Complete', 'Invoiced') 
  AND ( (MONTH(OrderDate) = MONTH(GETDATE()) AND day(OrderDate) <= DAY(GETDATE()))
   OR MONTH(OrderDate) < MONTH(GETDATE()))

Group by BILLNAME
HAVING COALESCE(SUM([2017]), SUM([2016])) IS NOT NULL
ORDER BY BILLNAME ASC

这是我从我的支点

获得的

enter image description here

我正在寻找类似的东西

enter image description here

2 个答案:

答案 0 :(得分:2)

您首先必须首先进行虚拟转移 DEMO

SELECT billname, 
       CAST([OrderperiodYear] as varchar(500)) + '_' + CAST([attribute] as varchar(500)) as attribute,
       [data]
FROM (SELECT billname, 
             [OrderperiodYear],
             [Sum_Buyprice] as Buy,
             [Sum_Sellprice] as Sell,
             [Tonnage] as Ton
      FROM records) p
UNPIVOT 
    ([data] FOR [attribute] IN 
                (Buy, Sell, Ton)
     ) as unpvt

<强>输出

enter image description here

然后您可以创建 Dynamic Pivot

答案 1 :(得分:1)

一个选项是跳过pivot()并转到旧样式交叉表。

select 
    billname
  , [2016_buyprice]  = sum(case when OrderPeriodYear = 2016 then sum_buyprice else null end)
  , [2017_buyprice]  = sum(case when OrderPeriodYear = 2017 then sum_buyprice else null end)
  , [2016_sellprice] = sum(case when OrderPeriodYear = 2016 then sum_sellprice else null end)
  , [2017_sellprice] = sum(case when OrderPeriodYear = 2017 then sum_sellprice else null end)
  , [2016_tonnage]   = sum(case when OrderPeriodYear = 2016 then tonnage else null end)
  , [2017_tonnage]   = sum(case when OrderPeriodYear = 2017 then tonnage else null end)
from sum_orders 
where OrderStatus in ('Complete', 'Invoiced') 
  and ((month(OrderDate) = month(getdate()) 
    and day(OrderDate) <= day(getdate()))
    or month(OrderDate) < month(getdate()))
group by billname
order by billname asc