今天图老师小编要跟大家分享Sql Server 字符串聚合函数,精心挑选的过程简单易学,喜欢的朋友一起来学习吧!
【 tulaoshi.com - 编程语言 】
如下表:AggregationTableIdName1赵2钱1孙1李2周如果想得到下图的聚合结果
(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/bianchengyuyan/)IdName1赵孙李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 
结果为:
IdName1赵孙李2钱周
来源:http://www.tulaoshi.com/n/20160219/1589203.html
看过《Sql Server 字符串聚合函数》的人还看了以下文章 更多>>