例如一张表中有字段3个:
     date         string1      string 2   三个字段
  2004-02-01       ab              qq
  2004-02-01       ab              cc
  2004-03-03       cd              bb
  2004-02-01       ef              qq
  2004-02-01       ef              cc
如何把相同date下的string1字段下不同的值相加成一个新字段,string2的值还是原来的成表如下:
    date          string1       string 2
  2004-02-01      ab,ef            qq
  2004-02-01      ab,ef            cc
  2004-03-03        cd             bb
   

解决方案 »

  1.   

    /*
    标题:按某字段合并字符串之一(简单合并)
    作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
    时间:2008-11-06
    地点:广东深圳描述:将如下形式的数据按id字段合并value字段。
    id    value
    ----- ------
    1     aa
    1     bb
    2     aaa
    2     bbb
    2     ccc
    需要得到结果:
    id     value
    ------ -----------
    1      aa,bb
    2      aaa,bbb,ccc
    即:group by id, 求 value 的和(字符串相加)
    */
    --1、sql2000中只能用自定义的函数解决
    create table tb(id int, value varchar(10))
    insert into tb values(1, 'aa')
    insert into tb values(1, 'bb')
    insert into tb values(2, 'aaa')
    insert into tb values(2, 'bbb')
    insert into tb values(2, 'ccc')
    gocreate function dbo.f_str(@id int) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(value as varchar) from tb where id = @id
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go--调用函数
    select id , value = dbo.f_str(id) from tb group by iddrop function dbo.f_str
    drop table tb
    --2、sql2005中的方法
    create table tb(id int, value varchar(10))
    insert into tb values(1, 'aa')
    insert into tb values(1, 'bb')
    insert into tb values(2, 'aaa')
    insert into tb values(2, 'bbb')
    insert into tb values(2, 'ccc')
    goselect id, [value] = stuff((select ',' + [value] from tb t where id = tb.id for xml path('')) , 1 , 1 , '')
    from tb
    group by iddrop table tb
    --3、使用游标合并数据
    create table tb(id int, value varchar(10))
    insert into tb values(1, 'aa')
    insert into tb values(1, 'bb')
    insert into tb values(2, 'aaa')
    insert into tb values(2, 'bbb')
    insert into tb values(2, 'ccc')
    go
    declare @t table(id int,value varchar(100))--定义结果集表变量
    --定义游标并进行合并处理
    declare my_cursor cursor local for
    select id , value from tb
    declare @id_old int , @id int , @value varchar(10) , @s varchar(100)
    open my_cursor
    fetch my_cursor into @id , @value
    select @id_old = @id , @s=''
    while @@FETCH_STATUS = 0
    begin
        if @id = @id_old
           select @s = @s + ',' + cast(@value as varchar)
        else
          begin
            insert @t values(@id_old , stuff(@s,1,1,''))
            select @s = ',' + cast(@value as varchar) , @id_old = @id
          end
        fetch my_cursor into @id , @value
    END
    insert @t values(@id_old , stuff(@s,1,1,''))
    close my_cursor
    deallocate my_cursorselect * from @t
    drop table tb
      

  2.   

    --sql 2000
    create function dbo.f_str(@date datetime,@string2 varchar(10)) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(string1 as varchar) from tb where date = @date and string2 = @string2
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go--调用函数
    select date , string1 = dbo.f_str(date,string2) , string2 from tb group by date , string2--sql 2005select date, [string1] = stuff((select ',' + [string1] from tb t where id = tb.date and string2 = tb.string2 for xml path('')) , 1 , 1 , '') , string2
    from tb
    group by date,string2
      

  3.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(小F,向高手学习)
    -- Date    :2010-04-23 11:00:52
    -- Verstion:
    --      Microsoft SQL Server 2005 - 9.00.4053.00 (Intel X86) 
    -- May 26 2009 14:24:20 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([date] datetime,[string1] varchar(2),[string2] varchar(2))
    insert [tb]
    select '2004-02-01','ab','qq' union all
    select '2004-02-01','ab','cc' union all
    select '2004-03-03','cd','bb' union all
    select '2004-02-01','ef','qq' union all
    select '2004-02-01','ef','cc'
    --------------开始查询--------------------------
    select
     date, [string1] = stuff((select ',' + [string1] from tb t where date = tb.date and string2 = tb.string2 for xml path('')) , 1 , 1 , '') , string2
    from
     tb
    group by
     date,string2
    ----------------结果----------------------------
    /* date                    string1                                                                                                                                                                                                                                                          string2
    ----------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            cc
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            qq
    2004-03-03 00:00:00.000 cd                                                                                                                                                                                                                                                               bb(3 行受影响)
    */
      

  4.   

    CREATE FUNCTION dbo.f_str
    (
    @date DATETIME
    )
    RETURNS VARCHAR(100)
    AS
    BEGIN
    DECLARE @str VARCHAR(1000)
    SET @str = ''
    SELECT @str = @str + ',' + CAST(string1 AS VARCHAR)
    FROM   tb
    WHERE  date = @date

    SET @str = RIGHT(@str, LEN(@str) - 1)
    RETURN @str
    END
    GO
    --调用函数
    SELECT date,
           string1 = dbo.f_str(date),
           string2
    FROM   tb
    GROUP BY
           date
      

  5.   

    --------------------------------------------------------------------------
    --  Author : htl258(Tony)
    --  Date   : 2010-04-23 10:58:57
    --  Version:Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
    --          Jul  9 2008 14:43:34 
    --          Copyright (c) 1988-2008 Microsoft Corporation
    --          Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)
    --  Blog   : http://blog.csdn.net/htl258
    --------------------------------------------------------------------------
    --> 生成测试数据表:tbIF NOT OBJECT_ID('[tb]') IS NULL
    DROP TABLE [tb]
    GO
    CREATE TABLE [tb]([date] DATETIME,[string1] NVARCHAR(10),[string2] NVARCHAR(10))
    INSERT [tb]
    SELECT N'2004-02-01','ab','qq' UNION ALL
    SELECT N'2004-02-01','ab','cc' UNION ALL
    SELECT N'2004-03-03','cd','bb' UNION ALL
    SELECT N'2004-02-01','ef','qq' UNION ALL
    SELECT N'2004-02-01','ef','cc'
    GO
    --SELECT * FROM [tb]-->SQL查询如下:
    select min(date) date,
    [string1]=stuff((select ','+[string1] from tb where [string2]=t.[string2] for xml path('')),1,1,''),
    [string2]
    from tb t
    group by [string2]
    /*
    date string1 string2
    2004-03-03 00:00:00.000 cd bb
    2004-02-01 00:00:00.000 ab,ef cc
    2004-02-01 00:00:00.000 ab,ef qq
    */
      

  6.   

    --sql 2000
    create table tb(date datetime,string1 varchar(10),string2 varchar(10))
    insert into tb values('2004-02-01', 'ab', 'qq')
    insert into tb values('2004-02-01', 'ab', 'cc')
    insert into tb values('2004-03-03', 'cd', 'bb')
    insert into tb values('2004-02-01', 'ef', 'qq')
    insert into tb values('2004-02-01', 'ef', 'cc')
    gocreate function dbo.f_str(@date datetime,@string2 varchar(10)) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(string1 as varchar) from tb where date = @date and string2 = @string2
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go--调用函数
    select date , string1 = dbo.f_str(date,string2) , string2 from tb group by date , string2drop function dbo.f_str
    drop table tb/*
    date                                                   string1                                                                                              string2    
    ------------------------------------------------------ ---------------------------------------------------------------------------------------------------- ---------- 
    2004-02-01 00:00:00.000                                ab,ef                                                                                                cc
    2004-02-01 00:00:00.000                                ab,ef                                                                                                qq
    2004-03-03 00:00:00.000                                cd                                                                                                   bb(所影响的行数为 3 行)*/
    --sql 2005
    create table tb(date datetime,string1 varchar(10),string2 varchar(10))
    insert into tb values('2004-02-01', 'ab', 'qq')
    insert into tb values('2004-02-01', 'ab', 'cc')
    insert into tb values('2004-03-03', 'cd', 'bb')
    insert into tb values('2004-02-01', 'ef', 'qq')
    insert into tb values('2004-02-01', 'ef', 'cc')
    goselect date, [string1] = stuff((select ',' + [string1] from tb t where date = tb.date and string2 = tb.string2 for xml path('')) , 1 , 1 , '') , string2
    from tb
    group by date,string2drop table tb/*
    date                    string1                                                                                                                                                                                                                                                          string2
    ----------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            cc
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            qq
    2004-03-03 00:00:00.000 cd                                                                                                                                                                                                                                                               bb(3 行受影响)*/
      

  7.   

    --------------------SQL Server数据格式化工具-------------------
    ---------------------------------------------------------------
    -- DESIGNER :happycell188(喜喜)
    --       QQ :584738179
    -- Development Tool :Microsoft Visual C++ 6.0    C Language 
    -- FUNCTION :CONVERT DATA TO T-SQL
    ---------------------------------------------------------------
    -- Microsoft SQL Server  2005
    -- Developer Edition on Microsoft Windows XP [版本 5.1.2600]
    ---------------------------------------------------------------
    ---------------------------------------------------------------use test
    go
    if object_id('test.dbo.tb') is not null drop table tb
    -- 创建数据表
    create table tb
    (
    date char(10),
    string1 char(3),
    string2 char(3)
    )
    go
    --插入测试数据
    insert into tb select '2004-02-01','ab','qq'
    union all select '2004-02-01','ab','cc'
    union all select '2004-03-03','cd','bb'
    union all select '2004-02-01','ef','qq'
    union all select '2004-02-01','ef','cc'
    go
    --代码实现select date=right(date,10),
    string1=stuff((select ','+rtrim(string1) from tb where date=t.date and string2=t.string2 for xml path('')),1,1,''),
    string2 from tb t
    group by date,string2
    /*测试结果date        string1  string2
    -------------------------------
    2004-02-01 ab,ef  cc 
    2004-02-01 ab,ef  qq 
    2004-03-03 cd       bb (3 行受影响)
    */
      

  8.   


    drop table tb;
    create table tb([date] datetime, string1 varchar(2),string2 varchar(2))
    insert into tb
    select '2004-02-01','ab','qq' union all
    select '2004-02-01','ab','cc' union all
    select '2004-03-03','cd','bb' union all
    select '2004-02-01','ef','qq' union all
    select '2004-02-01','ef','cc'createfunction f_strToLine(
        @date datetime
        ,@string2 varchar(2)
    )returns nvarchar(4000)
    as
    begin
        declare @str nvarchar(4000)    select @str = isnull(@str+',','') + string1
        from tb
        where [date] = @date and string2 = @string2
       
        return @str
    end--查询结果
    select [date], [str_line] = dbo.f_strToLine([date],string2),string2
    from tb--结果
    /*
    2004-02-01 00:00:00.000 ab,ef qq
    2004-02-01 00:00:00.000 ab,ef cc
    2004-03-03 00:00:00.000 cd bb
    2004-02-01 00:00:00.000 ab,ef qq
    2004-02-01 00:00:00.000 ab,ef cc
    */
      

  9.   

    还是不对。
    建表
    create  table test(
    date datetime ,
    char1 varchar(20),
    char2 varchar(20)
    )
    插入
    insert into test values('2004-01-02','ab','aaa')
    insert into test values('2004-01-02','cd','aaa')
    insert into test values('2004-01-04','qq','ff')
    insert into test values('2004-01-04','qq','dd')
    insert into test values('2004-01-03','ee','fff')
    insert into test values('2004-01-03','ds','fff')
    insert into test values('2004-01-01','qq','ff')
    查询
    select date,
    char1=stuff((select ','+rtrim(char1) from test where date=test.date and char2=t.char2 for xml path('')),1,1,''),
    char2 from test t
    group by date,char2 
    结果还是不对
      

  10.   

    判断依据是,date下的时间相同,string1下的字段不同才合并,并不是date下的时间相同,string2下的字段相同合并。
      

  11.   

    --> 生成测试数据表:tbIF NOT OBJECT_ID('[tb]') IS NULL
        DROP TABLE [tb]
    GO
    CREATE TABLE [tb]([date] DATETIME,[string1] NVARCHAR(10),[string2] NVARCHAR(10))
    INSERT [tb]
    SELECT N'2004-02-01','ab','qq' UNION ALL
    SELECT N'2004-02-01','ab','cc' UNION ALL
    SELECT N'2004-03-03','cd','bb' UNION ALL
    SELECT N'2004-02-01','ef','qq' UNION ALL
    SELECT N'2004-02-01','ef','cc'
    GO
    --SELECT * FROM [tb]-->SQL查询如下:
    select date,
        [string1]=stuff((select ','+[string1] from tb where date=t.date and [string2]=t.[string2] for xml path('')),1,1,''),
        [string2]
    from tb t
    group by date,[string2]
    /*
    date    string1    string2
    2004-02-01 00:00:00.000    ab,ef    cc
    2004-02-01 00:00:00.000    ab,ef    qq
    2004-03-03 00:00:00.000    cd    bb
    */用这样
      

  12.   

    --sql 2000
    create table tb(date datetime , string1 varchar(10),string2 varchar(10))
    insert into tb values('2004-02-01', 'ab', 'qq')
    insert into tb values('2004-02-01', 'ab', 'cc')
    insert into tb values('2004-03-03', 'cd', 'bb')
    insert into tb values('2004-02-01', 'ef', 'qq')
    insert into tb values('2004-02-01', 'ef', 'cc')
    gocreate function dbo.f_str(@date datetime) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(string1 as varchar) from (select distinct date , string1 from tb) t where date = @date
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go--调用函数
    select m.* , n.string2 from
    (select date , string1 = dbo.f_str(date) from (select distinct date , string1 from tb) t group by date) m
    cross join 
    (select distinct date , string2 from tb) n
    where m.date = n.datedrop function dbo.f_str
    drop table tb/*
    date                                                   string1                                                                                              string2    
    ------------------------------------------------------ ---------------------------------------------------------------------------------------------------- ---------- 
    2004-02-01 00:00:00.000                                ab,ef                                                                                                cc
    2004-02-01 00:00:00.000                                ab,ef                                                                                                qq
    2004-03-03 00:00:00.000                                cd                                                                                                   bb(所影响的行数为 3 行)*/--sql 2005
    create table tb(date datetime , string1 varchar(10),string2 varchar(10))
    insert into tb values('2004-02-01', 'ab', 'qq')
    insert into tb values('2004-02-01', 'ab', 'cc')
    insert into tb values('2004-03-03', 'cd', 'bb')
    insert into tb values('2004-02-01', 'ef', 'qq')
    insert into tb values('2004-02-01', 'ef', 'cc')
    go
    select m.* , n.string2 from
    (
    select date, [string1] = stuff((select ',' + [string1] from (select distinct date , string1 from tb) t where date = m.date for xml path('')) , 1 , 1 , '')
    from (select distinct date , string1 from tb) m
    group by date
    ) m
    cross join 
    (select distinct date , string2 from tb) n
    where m.date = n.datedrop table tb/*
    date                    string1                                                                                                                                                                                                                                                          string2
    ----------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            cc
    2004-02-01 00:00:00.000 ab,ef                                                                                                                                                                                                                                                            qq
    2004-03-03 00:00:00.000 cd                                                                                                                                                                                                                                                               bb(3 行受影响)*/
    虽然实现了你的需求,但是从结果来看,还不如7楼原来给你的方法.