Sql Server 字符串聚合函数
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.Aggregate
相关文档:
动态语句
1 :普通SQL语句可以用exec执行
Select * from tableName
exec('select * from tableName')
exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N
2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fnam ......
第一部分:SQL server与ACCESS数据库的交换
软件开发网
1. 在SQL SERVER里查询access数据: 软件开发网
SELECT * from OpenDataSource( 'Microsoft.Jet.OLEDB.4.0','Data Source="c:\DB.mdb";User ID=Admin;Password=')...表名
--------------------------------------------------------------------------
2. 将ac ......
我今天学习了Oracle数据库如何修改表的知识,是冯威老师讲的课,我做了简单的记录:
1.在表中插入新的列:
alter table tablename
add city varchar(2) default 'rr' //赋默认值
2.修改表中的列:
alter table tablename
modify city varchar(20)
3.删除表中的列:
alter t ......
(1)SQL方法(1)
select convert(varchar(5),dateadd(hour,number,cast('00:00' as datetime)),108)+'~'+
convert(varchar(5),dateadd(hour,number+1,cast('00:00' as datetime)),108) as [date]
from master..spt_values
where type = 'P' and
number <= 23
(2)SQL方法(2)
得出一天的时间段记录。(如&nb ......
if exists(select * from sysobjects where name='atzk')--判断是否存在此表
drop table atzk
go
create table atzk
(
nid int identity(1,1) primary key,--nid自动编号,并设为主键。
mytitle varchar(50) not null,--通知的标题。
mycontents varchar(200)--发布通知的内容。
) ......