具有多个结果值的 Pivot

PIvot with multiple result values

我试图在这个主元中输入多个和 table 但我没有成功,

这是原始数据 来自

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

这是我的支点我怎样才能在支点结果中包含购买价格和吨位

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

这是我从我的数据中心得到的

我正在寻找这样的东西

一种选择是跳过 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

您首先必须先进行逆轴旋转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

输出

然后你可以创建一个Dynamic Pivot.