日期:2014-05-17  浏览次数:20633 次

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

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
------------------------
id string
1 a,b,c,e,f
2 a,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
------------------------
id string
1 a,b,c,e,f
2 a,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函数的写法