之前,在论坛上搜索这类问题的解答,都是用自定义函数的方法。刚才想了一个用变量的解法。贴上来让大家看看,仅供交流、讨论、参考。
declare @s varchar(8000),@i int
create table #t ( id int,s varchar(100))
insert #t select 1,'a' union select 1,'b' union select 2,'a'
select * into #t0 from #t order by id
set @s=''
set @i=-1
update #t0 set @s=case when @i=id then @s+','+s else s end, @i=id, id=@i,s=@s
select id,max(s) from #t0 group by id
drop table #t,#t0