日期:2014-05-18  浏览次数:20558 次

问一个关于GROUP BY之后字符串求合的问题
SELECT   +   GROUP   BY   之后   用SUM就可以对某个int字段求和,但是怎么在使用SELECT   +   GROUP   BY   之后对字符串求合?比如
id     str
1       abc
1       def

得到的结果是
id     str
1       abcdef

如果要使用自建函数,请问这个函数怎么写。

------解决方案--------------------
--测试数据
create table csdn(id int,txt varchar(10))
insert csdn
select 1, 'a ' union all
select 1, 'b ' union all
select 1, 'c ' union all
select 2, 'aa ' union all
select 2, 'bb ' union all
select 2, 'cc ' union all
select 3, 'aaa ' union all
select 3, 'bbb '
select * from csdn
go

create function Gettxt(@id int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s= ' '
select @s=@s + ', ' +txt from csdn where id=@id
--return @s
return stuff(@s,1,1, ' ')
end
go

select id,dbo.Gettxt(id) txt from csdn group by id
go

drop function Gettxt
drop table csdn
go
------解决方案--------------------


create table tb(id int,str 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
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+str from tb where id=@id
return stuff(@r,1,1, ' ')
end
go

-- 调用函数
select id, dbo.fn_Merge(id) as str from tb group by id

go
drop table tb
drop function fn_Merge
------解决方案--------------------
SQL Server 2000中常见的有两种处理方式:

1、如上,写一个用户自定义函数。

2、用游标处理。

使用用户自定义函数是最简单的方法。