源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Sql Server 字符串聚合函数

  • 时间:2020-05-18 15:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Sql Server 字符串聚合函数
如下表:AggregationTable
Id Name
1
2
1
1
2
如果想得到下图的聚合结果
Id Name
1 赵孙李
2 钱周
利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是无法做到的。因为这些都是对数值的聚合。不过我们可以通过自定义函数的方式来解决这个问题。 [b]1.首先建立测试表,并插入测试数据: [/b]
[u]复制代码[/u] 代码如下:
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
[b]2.创建自定义字符串聚合函数 [/b]
[u]复制代码[/u] 代码如下:
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
[b]3.执行下面的语句,并查看结果[/b]
[u]复制代码[/u] 代码如下:
select dbo.AggregateString(Id),Id from AggregationTable group by Id
结果为:
Id Name
1 赵孙李
2 钱周
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部