標籤:style blog http color 使用 io ar for 資料
比如表中有兩列資料 :
id name
1 a
1 b
1 c
2 d
2 e
變成如下格式:
id name
1 a,b,c
2 d,e
資料:
if object_id(#表)is not null drop table #表select did,name, from #表 order by diddrop table #表select 66 nid,‘aaa‘ name,1 did into #表 union allselect 67,‘bbb‘,1 union allselect 80,‘ccc‘,1 union allselect 69,‘ddd‘,2 union allselect 70,‘eee‘,2
實現代碼如下:
--遞迴計算多行合并成一個欄位--方法1;with x (did, cnt, list, nid, le)as (select did,count(1)over(partition by did),cast(name as varchar(100)),nid,1 from #表union allselect x.did,x.cnt,cast(x.list+‘,‘+a.name as varchar(100)),a.nid,x.le+1 from #表 a,xwhere a.did=x.did and a.nid>x.nid)select * from xwhere le=cnt--方法2 中間表效率不好if object_id(#表)is not null drop table #結果select did,cast(name as varchar(2000)) name into #結果from #表 order by diddeclare @dept int =‘‘,@name varchar(max) =‘‘update aset @name= case when @dept=did then @name+‘,‘+name else name end, @dept=did, name=@namefrom #結果 aselect did,max(name) from #結果group by did--方法3 使用xml方便,簡單--select ‘,‘ + name from #表 for xml path(‘‘)select did, name = (stuff((select ‘,‘ + name from #表 where did = a.did for xml path(‘‘)),1,1,‘‘)) from #表 a group by did
結果:
SQL Server將相同id的另一列的多行內容拼接成一行