繁体   English   中英

将行值取消透视成多列

[英]unpivot row values into multiple columns

我具有以下结构:

http://sqlfiddle.com/#!6/0e72e/8

CREATE TABLE Prices
(
Day date,
ProductName nVARCHAR(10),
Location nVARCHAR(10),
RegPrice1 float,
SalePrice1 float,
SalePrice2 float
)

INSERT INTO Prices VALUES ('6/24/2014', 'xbox', 'NewYork',30,20,10)
INSERT INTO Prices VALUES ('6/24/2014', 'xbox', 'London', 100,80,60)
INSERT INTO Prices VALUES ('6/24/2014', 'xbox', 'Singapore', 70,50,30)
INSERT INTO Prices VALUES ('6/24/2014', 'watch1','NewYork', 500,400,300)
INSERT INTO Prices VALUES ('6/24/2014', 'watch1','London', 1000,800,600) 
INSERT INTO Prices VALUES ('6/24/2014', 'watch1','Singapore', 999,888,777) 

我想取消透视此表,因此它看起来像:

 Day Pr_Name PriceType NewYork London Singapore 2014-06-24 xbox RegPrice1 30 100 70 2014-06-24 xbox SalePrice1 20 80 50 2014-06-24 xbox SalePrice2 10 60 30 2014-06-24 watch1 RegPrice1 500 1000 999 2014-06-24 watch1 SalePrice1 400 800 888 2014-06-24 watch1 SalePrice1 300 600 777 

我可以取消旋转一层以获得NewYork列,但无法将伦敦和新加坡列设置到位。 我已经修改了以下代码以添加伦敦和新加坡,但未成功。 我只是保持不动吗?

select Day, ProductName, PriceType, NewYork
from (select * from Prices ) as t
Unpivot 
(
  NewYork for PriceType in (RegPrice1, SalePrice1, SalePrice2)

) As unpvt

我们可以使用CROSS APPLY取消定价,然后再应用PIVOT

SELECT 
*
FROM

  ( select Day, ProductName, Location, col,  value
    from Prices
    cross apply
    (
        select 'RegPrice1' , Prices.RegPrice1 union all
        select 'SalePrice1', Prices.SalePrice1 union all
        select 'SalePrice2', Prices.SalePrice2
    ) c (col, value)
  ) PD
  PIVOT
  ( max(value) for Location in ([NewYork],[London],[Singapore])
  )pvt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM