34,873
社区成员
发帖
与我相关
我的任务
分享
create table Tb(id int,iid bigint)
insert into Tb
select 1,1
union all select 1,2
union all select 1,3
union all select 2,1
union all select 2,2
union all select 2,3
declare @s varchar(8000)
set @s=''
select @s=@s+',max(case when iid='+rtrim(iid)+' then iid else 0 end) as [iid'+rtrim(iid)+']'
from (select distinct iid from Tb)t
exec('select id'+@s+' from Tb group by id')
/*
id iid1 iid2 iid3
----------- -------------------- -------------------- --------------------
1 1 2 3
2 1 2 3
*/