sqlserver中如何将一列数据拼接成一个字符串

我一个表A: Id numeric(18) Code varchar(10)
id code  
1 zhang
1 yan
2 zdw
2 ydj
得到以下的结果

1 zhang,yan
2 zdw,ydj

 

 

declare @T Table(Id numeric(18), Code varchar(10))
insert into @T(id,code)
select 1, 'zhang'
union all
select 1, 'yan'
union all
select 2, 'zdw'
union all
select 2, 'ydj';

SELECT B.id,LEFT(UserList,LEN(UserList)-1) code FROM (
SELECT id,(SELECT code+',' FROM @T WHERE id=A.id FOR XML PATH('')) AS UserList FROM @T A GROUP BY id
) B

你可能感兴趣的:(database)