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
begin
declare @r varchar(8000)
set @r=''
select @r=@r+';'+txt from tb where id=@id
return stuff(@r,1,1,'')
end
go
-- 调用函数
select id, dbo.fn_Merge(id) as txt from tb group by id
go
drop table tb
drop function fn_Merge
这条语句在2005是能执行出来的,可是2000里确不行,大家给看看,大概意思就是,我要得到 下面的结果
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
转自:http://topic.csdn.net/u/20100520/15/176afe53-0a0c-40cd-86ac-c2a3a3b41130.html
本文详细解析了SQL中如何使用聚合函数进行数据处理,并通过实例展示了如何利用函数实现特定的数据分组和输出需求。从创建表、插入数据,到定义聚合函数和调用函数,再到最终结果展示,一步步深入浅出地阐述了SQL在数据处理领域的强大能力。
3251

被折叠的 条评论
为什么被折叠?



