我有一张数据表。我需要以水平格式获取ID(第一列)和相关的2列数据。
对于ID,对应LinkID
出现的最大值为3。因此我们需要在3列之后开始显示PC相关数据。
我已将第4列中的“ID的总发生次数”计算为TotalnoofoccurenceofID
。
我的可用表是
ID LinkID PC TotalnoofoccurenceofID
10R46 R*1005 8017 2
10R46 R*10335 5019 2
100R91 R*1005 8017 1
10R91 R*243 8870 1
10M95 R*4918 8305 3
10M95 R*9017 8305 3
10M95 R*9470 8221 3
我想得到这样的结果集:
ID TotalnoofoccurenceofID LinkID1 LinkID2 LinkID3 PC1 PC2 PC3
10R46 2 R*1005 R*10335 8017 5019
100R91 1 R*1005 8017
10R91 1 R*243 8870
10M95 3 R*4918 R*9017 R*9470 8305 8305 8221
如果我描述结果集,那么
First row :ID 10R46 and related 2 LinkID(under LinkID1 and LinkID2) and related 2 PCs(under PC1 and PC2)
Second row :ID 100R91 and related 1 LinkID(under LinkID1) and related 1 PC(under PC1)
Third row :ID 10R91 and related 1 LinkID(under LinkID1) and related 1 PC(under PC1)
Fourth row :ID 10M95 and related 3 LinkID(under LinkID1,LinkID2,LinkID3) and related 3 PC(under PC1,PC2,PC3)
请注意,最大LinkID
次出现为3,PC列在3 LinkID
列之后开始。
非常感谢你。
答案 0 :(得分:1)
检查一下,
Declare @t table(ID varchar(50),LinkID varchar(50),PC int, TotalnoofoccurenceofID int)
insert into @t
select '10R46', 'R*1005', 8017, 2 union all
select '10R46', 'R*10335', 5019, 2 union all
select '100R91', 'R*1005', 8017, 1 union all
select '10R91', 'R*243', 8870, 1 union all
select '10M95', 'R*4918', 8305, 3 union all
select '10M95', 'R*9017', 8305, 3 union all
select '10M95', 'R*9470', 8221, 3
;with cte as
(select *,ROW_NUMBER()over(partition by id order by id)rn from @t)
select a.ID,b.LinkID,c.LinkID,d.LinkID,b.PC,c.PC,d.PC from cte a
left join cte b on a.id=b.id and b.rn=1
left join cte c on a.id=c.id and c.rn=2
left join cte d on a.id=d.id and d.rn=3
where a.rn=1