连接相同字段的字符串

来源:百度知道 编辑:UC知道 时间:2024/07/02 16:47:48
id txt
1 aaa
1 bbb
2 ccc
3 ddd
3 eee
3 fff

select id,***(txt,';') from tb group by id
结果:
1 aaa;bbb
2 ccc
3 ddd;eee;fff
以下是网上得的sql语句
create table tb(id int,txt varchar(100))
go
insert into tb
select 1,'aaa' union all
select 1,'bbb' union all
select 2,'ccc' union all
select 3,'ddd' union all
select 3,'eee' union all
select 3,'fff'

go
--写一个聚合函数:
create function dbo.fn_Merge(@id int)
returns varchar(8000)
as

还是这个问题,一条select语句可以完成,但是没有自定义函数来的方便
select实现如下:
select T.id,MAX(case when Num=1 then txt+';' else '' end)+
MAX(case when Num=2 then txt+';' else '' end)+
MAX(case when Num=3 then txt+';' else '' end)+
MAX(case when Num=4 then txt+';' else '' end)+
MAX(case when Num=5 then txt+';' else '' end)
from (select (select count(*) from tb where id=a.id and txt<=a.txt group by id) as num,
* from tb a) T group by T.id

可以的,ACC创建函数还麻烦
select T.id,MAX(case when Num=1 then txt+';' else '' end)+MAX(case when Num=2 then txt+';' else '' end)+MAX(case when Num=3 then txt+';' else '' end)+MAX(case when Num=4 then txt+';' else '' end)+MAX(case when Num=5 then txt+';' else '' end)from (select (select count(*) from tb where id=a.id and txt<=a.txt group by id) as num,* from tb a) T group by T.