34,576
社区成员
发帖
与我相关
我的任务
分享
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([a] int,[b] int,[c] varchar(1))
insert [tb]
select 1,123,'a' union all
select 2,234,'b' union all
select 3,345,'c' union all
select 4,456,'d' union all
select 5,234,'e' union all
select 6,345,'f' union all
select 7,234,'g'
---查询---
select
a=row_number() over(order by getdate()),
b,
c=stuff((select ','+c from tb where b=t.b for xml path('')),1,1,'')
from
tb t
group by
b
---结果---
a b c
-------------------- ----------- ----------------
1 123 a
2 234 b,e,g
3 345 c,f
4 456 d
(4 行受影响)