栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 数据库 > MySQL > MsSql

Sql Server 字符串聚合函数

MsSql 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Sql Server 字符串聚合函数

如下表: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 钱周

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/170712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号