首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问一上自定义聚合函数的写法

2013-03-12 
请教一下自定义聚合函数的写法use tempdbif object_id(test,u) is not null drop table testcreate ta

请教一下自定义聚合函数的写法


use tempdb
if object_id('test','u') is not null drop table test
create table test(id int,string nvarchar(max))
insert into test(id,string)
select 1,'a,b' union all
select 1,'b,c' union all
select 1,'e,f' union all
select 2,'a' union all
select 2,'a,c' union all
select 2,'c,e,f' 

--需求:想创建一个自定义的聚合函数实现如下结果
select id,dbo.test(string) as string from test
group by id
------------------------
idstring
1a,b,c,e,f
2a,c,e,f

--PS: 只是求自定义聚合函数的实现,而非其它方式,谢谢。


[解决办法]

use tempdb
if object_id('test','u') is not null drop table test
create table tb(id int,string nvarchar(max))
insert into tb(id,string)
select 1,'a,b' union all
select 1,'b,c' union all
select 1,'e,f' union all
select 2,'a' union all
select 2,'a,c' union all
select 2,'c,e,f' 

/*--需求:想创建一个自定义的聚合函数实现如下结果
select id,dbo.test(string) as string from test
group by id
------------------------
idstring
1a,b,c,e,f
2a,c,e,f

--PS: 只是求自定义聚合函数的实现,而非其它方式,谢谢。*/

create function test(@str nvarchar(max))
returns @tb table (col varchar(20))
as
begin
     set @str=@str+','
     while charindex(',',@str)>0
     begin
          insert into @tb
                select left(@str,charindex(',',@str)-1)
          set @str=stuff(@str,1,charindex(',',@str),'')      
     end
     return
end

with cte as
(
 select distinct id, b.*
 from tb a cross apply dbo.test(string) b
)

select id,
 string=stuff((select ','+col from cte where id=a.id for xml path('')),1,1,'')
from cte  a group by id
[解决办法]
没有自定义聚集函数,只有clr自定义聚集函数,需要的话自己研究下clr函数的写法

热点排行