将行值展开为多列

时间:2014-09-18 17:59:35

标签: sql unpivot

我有以下结构:

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

1 个答案:

答案 0 :(得分:2)

我们可以使用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