如何把重复的行合并?
如何把重复的行合并?
有表TAB如下
ID DESC
1 A
2 B
1 C
合并后得到如下结果
ID DESC
1 A,C
2 B
依此类推,有多个重复的则以‘,’分隔
------解决方案--------------------create table test(ID int,[DESC] varchar(10))
insert test select 1, 'A '
union all select 2, 'B '
union all select 1, 'C '
create function dbo.fn_Merge(@ID int)
returns varchar(8000)
as
begin
declare @name varchar(8000)
set @name= ' '
select @name=@name+ ', '+[DESC] from test where ID=@ID
return stuff(@name,1,1, ' ')
end
go
select ID, dbo.fn_Merge(ID) as ID from test group by ID
drop table test
drop function fn_Merge
ID ID
----------- ----
1 A,C
2 B