Sql Server 字符串聚合函数
2022-11-12 09:50:04
内容摘要
这篇文章主要为大家详细介绍了Sql Server 字符串聚合函数,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!如下表:AggregationTable
文章正文
这篇文章主要为大家详细介绍了Sql Server 字符串聚合函数,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
如下表:AggregationTableId | Name |
1 | 赵 |
2 | 钱 |
1 | 孙 |
1 | 李 |
2 | 周 |
如果想得到下图的聚合结果
Id | Name |
1 | 赵孙李 |
2 | 钱周 |
利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是无法做到的。因为这些都是对数值的聚合。不过我们可以通过自定义函数的方式来解决这个问题。1.首先建立测试表,并插入测试数据:
代码如下:
1 2 3 4 5 6 7 8 9 10 | <code>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 </code> |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <code>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 </code> |
代码如下:
1 2 3 | <code>select dbo.AggregateString(Id),Id from AggregationTable group by Id </code> |
结果为:
Id | Name |
1 | 赵孙李 |
2 | 钱周 |
注:关于Sql Server 字符串聚合函数的内容就先介绍到这里,更多相关文章的可以留意
代码注释