SQL Server將相同id的另一列的多行內容拼接成一行


比如表中有兩列數據 :

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 did
drop table #表
select 66 nid,'aaa' name,1 did into #表 union all
select 67,'bbb',1 union all
select 80,'ccc',1 union all
select 69,'ddd',2 union all
select 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 all
select x.did,x.cnt,cast(x.list+','+a.name as varchar(100)),a.nid,x.le+1 from #表 a,x
where a.did=x.did and a.nid>x.nid
)
select * from  x
where le=cnt


--方法2 中間表效率不好
if object_id(#表)is not null drop table #結果

select did,cast(name as varchar(2000)) name 
into #結果
from #表 
order by did

declare @dept int ='',@name varchar(max) =''
update a
set @name= case when @dept=did then @name+','+name
            else name
            end,
    @dept=did,
    name=@name
from #結果 a
select 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  

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM