易截截图软件、单文件、免安装、纯绿色、仅160KB

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


相关文档:

航空公司管理系统(VC++ 与SQL 2005)

系统环境:Windows 7
软件环境:Visual C++ 2008 SP1 +SQL Server 2005
本次目的:编写一个航空管理系统
      这是数据库课程设计的成果,虽然成绩不佳,但是作为我用VC++ 以来编写的最大程序还是传到网上,以供参考。用VC++ 做数据库设计并不容易,但也不是不可能。以下是我的程序界面,后面 ......

用C#读SQL SERVER到控制台的简单示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
//sqlserver身份验证
//string sqlconn = "ser ......

个人总结的几条比较有意思的sql语句


 
--------------------------------------------------------------------
-- 作者:张爱国
-- 日期:2010-01-23 15:00:17
-- 描述: 一些比较有意思的SQL语句
-- Version:
--    Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)
--    Feb  9 2007 22:47:0 ......

SQL脚本创建表

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)--发布通知的内容。
 ) ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号