易截截图软件、单文件、免安装、纯绿色、仅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


相关文档:

SQL类型

SQL Server数据类型2009年02月02日 星期一 11:20数据类型是数据的一种属性,是数据所表示信息的类型。任何一种语言都有它自己所固有的数据类型,SQL Server提供一下25种固有的数据类型。 SQL Server数据类型一览表
  ·Binary [(n)]
·Varbinary [(n)]
·Char [(n)]
·Varchar[(n)]
· ......

oracle PL/SQL 中常量和变量的声明

 
一、常用数据类型:
Number:数字类型
Int:整数型
Pls_integer:整数型,产生溢出的错误
Binary_integer:整数型
Char:定长字符,最长255个字符
Varchar2:变长字符,最长2000个字符
Long:变长字符,最长2GB
Date:日期型
Boolean:布尔型
二、定义常量
格式:常量名   constant &nbs ......

用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 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号