(转) Sql Server 字符串聚合函数
来源:互联网 发布:单身 知乎 编辑:程序博客网 时间:2024/06/15 15:05
Sql Server 有如下几种聚合函数SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN,但是这些函数都只能聚合数值类型,无法聚合字符串。如下表:AggregationTable
Id Name
1 赵
2 钱
1 孙
1 李
2 周
如果想得到下图的聚合结果
Id Name
1 赵孙李
2 钱周
利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是无法做到的。因为这些都是对数值的聚合。不过我们可以通过自定义函数的方式来解决这个问题。
1.首先建立测试表,并插入测试数据:
view plaincopy to clipboardprint?
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
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.创建自定义字符串聚合函数
view plaincopy to clipboardprint?
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
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.执行下面的语句,并查看结果
view plaincopy to clipboardprint?
select dbo.AggregateString(Id),Id from AggregationTable
group by Id
select dbo.AggregateString(Id),Id from AggregationTable
group by Id
结果为:
Id Name
1 赵孙李
2 钱周
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/tjvictor/archive/2009/06/22/4289027.aspx
- (转) Sql Server 字符串聚合函数
- Sql Server 字符串聚合函数
- Sql Server 字符串聚合函数
- 自定义Sql Server 字符串聚合函数
- 字符串+聚合函数 (SQL)
- SQL Server聚合函数
- SQL Server 2017 新的字符串聚合函数String_Agg
- SQL Server聚合函数总结
- SQL-字符串连接聚合函数
- SQL Server 2005---聚合函数(分组函数)
- SQL Server 2005---聚合函数(分组函数)
- sql server 2005 聚合函数计算(2)
- Microsoft SQL Server学习(五)--操作符聚合函数
- SQL Server 2005 自定义聚合函数应用
- sql server 2005聚合函数计算
- 例说SQL Server 2008 聚合函数
- sql server 字符串函数
- sql server字符串函数
- iframe高度自适应
- 搜狗状告腾讯拼音输入法不正当竞争索赔2051万
- Java中数据库连接池原理机制的详细讲解
- 解析codepage和charset的含义及其应用
- 开发人员一定要加入收藏夹的网站
- (转) Sql Server 字符串聚合函数
- 十余家知名博客首度联手打造中国博客大赛
- 剖析Linux系统中硬链接与软链接的区别
- javascript 判断是否为低于1的百分数,并将之转换为浮点数
- 安装2000数据库的时候挂起
- 如何教育孩子
- Ehcache 1.5.0 User Guide - Cache Concepts (缓存概念)
- Creating a New Window Group
- 聚友网任命魏来为首席执行官