Sql Server 字符串聚合函数
时间:2024-01-17 08:15:34
如下表: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
结果为:
Id | Name |
1 | 赵孙李 |
2 | 钱周 |
标签:Sql,Server,字符串聚合
0
投稿
猜你喜欢
python利用proxybroker构建爬虫免费IP代理池的实现
2021-10-25 21:18:25
Django查询优化及ajax编码格式原理解析
2021-04-26 02:04:27
用好FrontPage2003的九大功能
2008-02-21 14:29:00
Python2.x版本中maketrans()方法的使用介绍
2021-02-14 21:04:25
Python文本终端GUI框架示例详细讲解
2021-05-19 22:47:12
十个Python经典小游戏的代码合集
2021-08-03 12:09:38
一个php Mysql类 可以参考学习熟悉下
2024-06-05 09:22:57
pandas之分组groupby()的使用整理与总结
2022-04-23 17:24:42
使用SQL SERVER存储过程实现历史数据迁移方式
2024-01-13 04:07:40
Python创建多线程的两种常用方法总结
2023-11-16 16:41:09
Python机器学习之AdaBoost算法
2021-03-13 08:07:18
php基于curl实现随机ip地址抓取内容的方法
2023-11-14 22:29:45
JS实现弹出下载对话框及常见文件类型的下载
2024-04-23 09:07:05
php中iconv函数使用方法
2023-06-12 08:11:07
Python splitlines使用技巧
2023-01-11 01:13:56
Python中seaborn库之countplot的数据可视化使用
2023-08-10 20:38:56
常见前端面试题及答案
2023-07-10 08:57:30
asp获取远程网页的指定内容的实现代码
2011-02-16 10:41:00
Python编写淘宝秒杀脚本
2021-01-31 23:23:42
10个php函数实用却不常见
2023-11-05 01:40:43