自交叉应用表格数据

时间:2018-07-31 14:14:31

标签: sql-server sql-server-2008

我有一个下表

ID       Level  StoreId   
2678540   3      A
2678540   7      A
2678540   3      B
2678540   7      B
2678540   3      C

我需要像下面这样

ID      A   B   C   D   E    
2678540 3   3   3   0   0
2678540 3   7   3   0   0
2678540 7   3   3   0   0
2678540 7   7   3   0   0

请帮助我实现这一目标。

1 个答案:

答案 0 :(得分:0)

如果StoreID'A'始终存在:

select tA.ID, tA.Level as A, tB.Level as B, tC.Level as C , 0 as D, 0 as E
from Table1 tA 
cross apply (select Level from Table1 t2 where tA.Id=t2.Id and t2.StoreId = 'B') tB
cross apply (select Level from Table1 t2 where tA.Id=t2.Id and t2.StoreId = 'C') tC
where tA.StoreId = 'A'