加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 数据库 > MsSql > 正文

Sql Server 字符串聚合函数

发布时间:2020-05-23 22:28:56 所属栏目:MsSql 来源:互联网
导读:Sql Server 字符串聚合函数

感兴趣的小伙伴,下面一起跟随脚本之家 jb51.cc的小编两巴掌来看看吧!

如下表:AggregationTable

如果想得到下图的聚合结果

利用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 
 

 

结果为:

 

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读