将这样的一张表
col1     col2      col3
-------------------------
4  6 11111
5  6 11111
4  7 2222
5  7 2222
查询出
4   6,7 11111,2222
5   6,7 11111,2222
sql语句怎么写?
请高人指教

解决方案 »

  1.   

    create TABLE TT (id varchar(32),type varchar(32),billMoney decimal(12,2))
    INSERT INTO TT
            SELECT '10001','支票',2000
    UNION ALL 
           SELECT '10001','预留款',1000
    UNION ALL 
            SELECT '10001','现金',800
    UNION ALL 
           SELECT '10002','挂账',1000
    UNION ALL 
            SELECT '10002','现金',800create function dbo.FC_Str(@id int)
    returns varchar(1000)
    as
    begin
      declare @str varchar(1000)
      set @str='' 
      select @str=@str+','+type+':'+cast(billMoney as varchar) from TT where id=@id
      return stuff(@str,1,1,'')
    endselect id,sum(billMoney) payedMoney,dbo.FC_Str(id) from TT group by id本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ws_hgo/archive/2009/03/17/3999390.aspx
      

  2.   

    合并列值 
    --*******************************************************************************************
    表结构,数据如下: 
    id    value 
    ----- ------ 
    1    aa 
    1    bb 
    2    aaa 
    2    bbb 
    2    ccc 需要得到结果: 
    id    values 
    ------ ----------- 
    1      aa,bb 
    2      aaa,bbb,ccc 
    即:group by id, 求 value 的和(字符串相加) 1. 旧的解决方法(在sql server 2000中只能用函数解决。) 
    --=============================================================================
    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 
    --1. 创建处理函数 
    CREATE FUNCTION dbo.f_strUnite(@id int) 
    RETURNS varchar(8000) 
    AS 
    BEGIN 
        DECLARE @str varchar(8000) 
        SET @str = '' 
        SELECT @str = @str + ',' + value FROM tb WHERE id=@id 
        RETURN STUFF(@str, 1, 1, '') 
    END 
    GO 
    -- 调用函数 
    SELECt id, value = dbo.f_strUnite(id) FROM tb GROUP BY id 
    drop table tb 
    drop function dbo.f_strUnite 
    go
    /* 
    id          value      
    ----------- ----------- 
    1          aa,bb 
    2          aaa,bbb,ccc 
    (所影响的行数为 2 行) 
    */ 
    --===================================================================================
    2. 新的解决方法(在sql server 2005中用OUTER APPLY等解决。) 
    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 
    -- 查询处理 
    SELECT * FROM(SELECT DISTINCT id FROM tb)A OUTER APPLY( 
            SELECT [values]= STUFF(REPLACE(REPLACE( 
                ( 
                    SELECT value FROM tb N 
                    WHERE id = A.id 
                    FOR XML AUTO 
                ), ' <N value="', ','), '"/>', ''), 1, 1, '') 
    )N 
    drop table tb /* 
    id          values 
    ----------- ----------- 
    1          aa,bb 
    2          aaa,bbb,ccc (2 行受影响) 
    */ --SQL2005中的方法2 
    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 select id, [values]=stuff((select ','+[value] from tb t where id=tb.id for xml path('')), 1, 1, '') 
    from tb 
    group by id /* 
    id          values 
    ----------- -------------------- 
    1          aa,bb 
    2          aaa,bbb,ccc (2 row(s) affected) */ drop table tb 
    合并列值,请参考!
      

  3.   

    ------字符串拆分/*
    标题:分拆列值1
    作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
    时间:2008-11-20
    地点:广东深圳
    描述有表tb, 如下:
    id          value
    ----------- -----------
    1           aa,bb
    2           aaa,bbb,ccc
    欲按id,分拆value列, 分拆后结果如下:
    id          value
    ----------- --------
    1           aa
    1           bb
    2           aaa
    2           bbb
    2           ccc
    */--1. 旧的解决方法(sql server 2000)
    SELECT TOP 8000 id = IDENTITY(int, 1, 1) INTO # FROM syscolumns a, syscolumns b SELECT A.id, SUBSTRING(A.[values], B.id, CHARINDEX(',', A.[values] + ',', B.id) - B.id)
    FROM tb A, # B
    WHERE SUBSTRING(',' + A.[values], B.id, 1) = ','DROP TABLE #--2. 新的解决方法(sql server 2005) 
    create table tb(id int,value varchar(30))
    insert into tb values(1,'aa,bb')
    insert into tb values(2,'aaa,bbb,ccc')
    go
    SELECT A.id, B.value
    FROM(
        SELECT id, [value] = CONVERT(xml,'<root><v>' + REPLACE([value], ',', '</v><v>') + '</v></root>') FROM tb
    )A
    OUTER APPLY(
        SELECT value = N.v.value('.', 'varchar(100)') FROM A.[value].nodes('/root/v') N(v)
    )BDROP TABLE tb/*
    id          value
    ----------- ------------------------------
    1           aa
    1           bb
    2           aaa
    2           bbb
    2           ccc(5 行受影响)
    */字符串合并----------------------------------------------------------/*
    标题:按某字段合并字符串之一(简单合并)
    作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
    时间: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------------------------------------------------改编,Tonyalter function dbo.f_str(@id int) returns varchar(1000)
    as
    begin
        declare @str varchar(1000)
        select @str = isnull(@str + ',','')+ value from tb where id = @id
        return @str
    end
    go--调用函数
    select id , value = dbo.f_str(id) from tb group by id--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
      

  4.   

    if OBJECT_ID('tb') is not null
    drop table tb
    go
    create table tb(col1 int,col2 nvarchar(20),col3  nvarchar(20))  
    go
    insert into tb values(4,'6 ','11111')
    insert into tb values(5,'6 ','11111')
    insert into tb values(4,'7 ','2222')
    insert into tb values(5,'7 ','2222')
     select col1,
    col2=isnull(stuff((select ','+rtrim(col2) from tb where t.col1=col1 for XML path('')),1,1,''),''),
    col3=isnull(stuff((select ','+rtrim(col3) from tb where t.col1=col1 for XML path('')),1,1,''),'')
    from tb t
    group by col14 6,7 11111,2222
    5 6,7 11111,2222
      

  5.   

    --sql 2000用如下函数实现.
    create table tb(col1 int,   col2 int,     col3 varchar(10))
    insert into tb values(4 ,6 ,'11111') 
    insert into tb values(5 ,6 ,'11111') 
    insert into tb values(4 ,7 ,'2222') 
    insert into tb values(5 ,7 ,'2222')
    gocreate function dbo.f_str1(@col1 int) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(col2 as varchar) from tb where col1 = @col1
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go
    create function dbo.f_str2(@col1 int) returns varchar(100)
    as
    begin
        declare @str varchar(1000)
        set @str = ''
        select @str = @str + ',' + cast(col3 as varchar) from tb where col1 = @col1
        set @str = right(@str , len(@str) - 1)
        return @str
    end
    go--调用函数
    select col1 , col2 = dbo.f_str1(col1) , col3 = dbo.f_str2(col1) from tb group by col1drop function dbo.f_str1,dbo.f_str2drop table tb/*
    col1        col2                                                                                                 col3                                                                                                 
    ----------- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- 
    4           6,7                                                                                                  11111,2222
    5           6,7                                                                                                  11111,2222(所影响的行数为 2 行)*/
    --sql 2005参考如下:
    /*
    标题:按某字段合并字符串之一(简单合并)
    作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
    时间: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
      

  6.   

    ----------------------------------------------------------------
    -- Author  :SQL77(只为思齐老)
    -- Date    :2010-01-07 09:39:16
    -- Version:
    --      Microsoft SQL Server  2000 - 8.00.194 (Intel X86) 
    -- Aug  6 2000 00:57:48 
    -- Copyright (c) 1988-2000 Microsoft Corporation
    -- Desktop Engine 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]([col1] int,[col2] int,[col3] int)
    insert [TB]
    select 4,6,11111 union all
    select 5,6,11111 union all
    select 4,7,2222 union all
    select 5,7,2222
    --------------开始查询--------------------------
    CREATE  FUNCTION GET_STRINGcol2(@col1 int)
    RETURNS VARCHAR(50)
    AS 
      BEGIN 
           DECLARE @CLASS VARCHAR(50)
           SELECT @CLASS=ISNULL(@CLASS+',','')+LTRIM(col2) FROM TB WHERE col1=@col1 
           RETURN @CLASS
      ENDCREATE  FUNCTION GET_STRINGcol3(@col1 int)
    RETURNS VARCHAR(50)
    AS 
      BEGIN 
           DECLARE @CLASS VARCHAR(50)
           SELECT @CLASS=ISNULL(@CLASS+',','')+LTRIM(col3) FROM TB WHERE col1=@col1 
           RETURN @CLASS
      END
    SELECT COL1,DBO.GET_STRINGcol2(COL1)COL2,DBO.GET_STRINGcol3(COL1)COL3 FROM TB GROUP BY COL1
    ----------------结果----------------------------
    /* 
    COL1        COL2                                               COL3                                               
    ----------- -------------------------------------------------- -------------------------------------------------- 
    4           6,7                                                11111,2222
    5           6,7                                                11111,2222(所影响的行数为 2 行)
    */
      

  7.   

    --------------------------------------------------------------------------
    --  Author : htl258(Tony)
    --  Date   : 2010-01-07 09:39:47
    --  Version:Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86) 
    --          Mar 29 2009 10:27:29 
    --          Copyright (c) 1988-2008 Microsoft Corporation
    --          Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 2)
    --------------------------------------------------------------------------
    --> 生成测试数据表:tbIF NOT OBJECT_ID('[tb]') IS NULL
    DROP TABLE [tb]
    GO
    CREATE TABLE [tb]([col1] INT,[col2] varchar(10),[col3] varchar(10))
    INSERT [tb]
    SELECT 4,6,11111 UNION ALL
    SELECT 5,6,11111 UNION ALL
    SELECT 4,7,2222 UNION ALL
    SELECT 5,7,2222
    GO
    --SELECT * FROM [tb]-->SQL查询如下:
    if OBJECT_ID('fn_test') is not null 
       drop function fn_test
    go
    create function fn_test(@col1 int,@col int)
    returns varchar(100)
    as
    begin
        declare @s varchar(100)
        if @col=1
        select @s=isnull(@s+',','')+col2 from tb where col1=@col1
        else
        select @s=isnull(@s+',','')+col3 from tb where col1=@col1
        return @s
    end
    goselect distinct col1, dbo.fn_test(col1,1) as col2,dbo.fn_test(col1,2) col3 from tb 
    /*
    col1 col2 col3
    4 6,7 11111,2222
    5 6,7 11111,2222
    */