SQL:同一個字段多個值,實現動態行轉列

原文鏈接:https://zhidao.baidu.com/question/871893841426870532.html
--用動態sql實現行轉列。因用到了row_number,只適用於sql server 2005及以上版本
--測試數據
with 
[user](ID,name,roleid) 
as(
select 1,'bobo','r1' union all
select 2,'coco','r1' union all
select 3,'dodo','r1' union all
select 4,'eoeo','r2' union all
select 5,'fofo','r2'),
[role](ID,name)
as(
select 'r1','admin' union all
select 'r2','user')
--兩表聯合查詢後暫存入臨時表
select b.ID roleid,b.name rolename,a.name username,row_number() over (partition by b.ID order by a.ID) seq
into #t
from [user] a 
inner join [role] b on a.roleid=b.ID;
--拼接動態sql
declare @sql varchar(max);
set @sql='';
select @sql=@sql+
',max(case seq when '+cast(tt.seq as varchar)+' then username else '''' end) user'+cast(tt.seq as varchar)
from (select distinct seq from #t) tt
order by seq;
set @sql='select rolename'+@sql+' from #t group by roleid,rolename';
--打印動態sql
select @sql;
--執行動態sql
exec(@sql);
--刪除臨時表
drop table #t;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章