Sql 将行值取消绑定到多列
我的结构如下: 我想取消此表的拆分,使其看起来像: 我能拆开一层以得到纽约专栏,但我还不能得到伦敦和新加坡专栏。我修改了下面的代码,添加了伦敦和新加坡,但没有成功。我是不是只是不去激励Sql 将行值取消绑定到多列,sql,unpivot,Sql,Unpivot,我的结构如下: 我想取消此表的拆分,使其看起来像: 我能拆开一层以得到纽约专栏,但我还不能得到伦敦和新加坡专栏。我修改了下面的代码,添加了伦敦和新加坡,但没有成功。我是不是只是不去激励 select Day, ProductName, PriceType, NewYork from (select * from Prices ) as t Unpivot ( NewYork for PriceType in (RegPrice1, SalePrice1, SalePrice2) ) A
select Day, ProductName, PriceType, NewYork
from (select * from Prices ) as t
Unpivot
(
NewYork for PriceType in (RegPrice1, SalePrice1, SalePrice2)
) As unpvt
我们可以使用交叉应用取消定价,然后应用透视
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
谢谢你的快速回复。我觉得这不是我想要的。我想把所有的价格类型堆叠在一列中。请看上面的结果表(我用完整的结果表更新了它)。更新了它,但仍然认为有更好的方法,我们可以先取消pivot,然后需要透视
select Day, ProductName, PriceType, NewYork
from (select * from Prices ) as t
Unpivot
(
NewYork for PriceType in (RegPrice1, SalePrice1, SalePrice2)
) As unpvt
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