create table #aa(id int identity(1,1),col1 char(1),col2 int,col3 varchar(30))
insert #aa(col1,col2)
select 'A' , 1
union all select 'A' , 3
union all select 'B' , 2
union all select 'B' , 3
union all select 'B' , 4
declare @ii varchar(30),@col1 char(1),@col3 varchar(10)
set @ii=''
set @col3=''
update #aa
set col3=@col3,@col3=(case when col1=@col1 then @col3+','+cast(col2 as varchar(10)) else cast(col2 as varchar(10)) end),@col1=col1
from #aa
select col1,max(col3) from #aa group by col1
drop table #aa
---结果:
col1 col3
---- ------------------------------
A 1,3
B 2,3,4
看来只能使用以下方法了:
create table tb(F1 varchar(10),F2 varchar(10))
insert tb select '00000001','Sandy'
union all select '00000001','Bob'
union all select '00000002', 'Sandy'
union all select '00000002', 'Don'
union all select '00000002', 'Chris'
union all select '00000003' ,'Karol'
union all select '00000004','Bob'
union all select '00000005' ,'Sandy'
union all select '00000005' ,'Jamie'
union all select '00000005','Bob'
go
set nocount on
select f1,f2=cast(f2 as varchar(8000)) into #t from tb order by f1
declare @f1 varchar(10),@r varchar(8000)
update #t set @r=case f1 when @f1 then @r+'',''+f2 else f2 end,f2=@r,@f1=f1
select F1,F2=max(f2) from #t group by f1