Sql Server 字符串聚合函数
Sql Server 有如下几种聚合函数SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN,但是这些函数都只能聚合数值类型,无法聚合字符串。如下表:AggregationTableIdName1赵2钱1孙1李2周 如果想得到下图的聚合结果
IdName1赵孙李2钱周 利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是无法做到的。因为这些都是对数值的聚合。不过我们可以通过自定义函数的方式来解决这个问题。
1.首先建立测试表,并插入测试数据:
create table AggregationTable(Id int, varchar(10))goinsert into AggregationTableselect 1,'赵' union allselect 2,'钱' union allselect 1,'孙' union allselect 1,'李' union allselect 2,'周'go
2.创建自定义字符串聚合函数
Create FUNCTION AggregateString(@Id int)RETURNS varchar(1024)ASBEGINdeclare @Str varchar(1024)set @Str = ''select @Str = @Str + from AggregationTablewhere = @Idreturn @StrENDGO
3.执行下面的语句,并查看结果
select dbo.AggregateString(Id),Id from AggregationTablegroup by Id
结果为:
IdName1赵孙李2钱周
页:
[1]