Sql Server 字符串聚合函数

Sql Server 有如下几种聚合函数SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN,但是这些函数都只能聚合数值类型,无法聚合字符串。

如下表:AggregationTable

Id   Name

1   赵

2   钱

1   孙

1   李

2   周

如果想得到下图的聚合结果

Id  Name

1   赵孙李

2   钱周

利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是无法做到的。因为这些都是对数值的聚合。不过我们可以通过自定义函数的方式来解决这个问题。
1.首先建立测试表,并插入测试数据:

create table AggregationTable(Id int, [Name] varchar(10))
go
insert into AggregationTable
select 1,'赵' union all
select 2,'钱' union all
select 1,'孙' union all
select 1,'李' union all
select 2,'周'
go

2.创建自定义字符串聚合函数

Create FUNCTION AggregateString
(
@Id int
)
RETURNS varchar(1024)
AS
BEGIN
declare @Str varchar(1024)
set @Str = ''
select @Str = @Str + [Name] from AggregationTable
where [Id] = @Id
return @Str
END
GO

3.执行下面的语句,并查看结果

select dbo.AggregateString(Id),Id from AggregationTable
group by Id

http://www.jb51.net/article/18772.htm

http://ephon.spaces.live.com/blog/cns!796FAD06E2C0A525!732.entry?wa=wsignin1.0&sa=144422700

http://www.cnblogs.com/blues_/archive/2010/03/19/1690047.html

http://soft.zdnet.com.cn/software_zone/2009/1202/1532996.shtml

字符串连接聚合函数

原文地址:https://www.cnblogs.com/emanlee/p/1768231.html