问一个关于GROUP BY之后字符串求合的问题

kingofmatch 2007-08-11 08:42:25
SELECT + GROUP BY 之后 用SUM就可以对某个int字段求和,但是怎么在使用SELECT + GROUP BY 之后对字符串求合?比如
id str
1 abc
1 def

得到的结果是
id str
1 abcdef

如果要使用自建函数,请问这个函数怎么写。
...全文
232 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
OracleRoob 2007-08-11
  • 打赏
  • 举报
回复
SQL Server 2000中常见的有两种处理方式:

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

2、用游标处理。

使用用户自定义函数是最简单的方法。
OracleRoob 2007-08-11
  • 打赏
  • 举报
回复


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
九斤半 2007-08-11
  • 打赏
  • 举报
回复
--测试数据
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

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧