a    name     c
001  abc   鞍山
002  bcd   沈阳
003  bcd   沈阳
004  bcd   大连
005  cdf   大连
006  cdf   大连
现在想得到的结果是a          name       c
001         abc       鞍山
002,003     bcd       沈阳
004         bcd       大连
005,006     cdf       大连如果name和c字段都相同,则合并用逗号分隔

解决方案 »

  1.   


    ;with cte as(
    select '001' as a,'abc' as name,'鞍山' as c
    union all select '002','bcd','沈阳'
    union all select '003','bcd','沈阳'
    union all select '004','bcd','大连'
    union all select '005','cdf','大连'
    union all select '006','cdf','大连'
    )select stuff((select ','+a from cte b 
           where b.c=a.c and a.name=b.name
           for xml path('')),1,1,'') 'a'
           ,a.name,a.c
    from cte a
    group by  a.name,a.c
    order by c/*
    a name c
    001 abc 鞍山
    004 bcd 大连
    005,006 cdf 大连
    002,003 bcd 沈阳
    */
      

  2.   

    if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
    go
    create table #temp( [a] varchar(100), [name] varchar(100), [c] varchar(100));
    insert #temp
    select '001','abc','鞍山' union all
    select '002','bcd','沈阳' union all
    select '003','bcd','沈阳' union all
    select '004','bcd','大连' union all
    select '005','cdf','大连' union all
    select '006','cdf','大连' --SQL:
    SELECT
    a = STUFF((SELECT ','+a FROM #temp b WHERE b.c=a.c AND b.name=a.NAME ORDER BY b.a FOR XML PATH('')),1,1,''),
    a.NAME,
    a.c
    FROM #temp A
    GROUP BY a.name, a.c
    ORDER BY MIN(a.a)/*
    a NAME c
    001 abc 鞍山
    002,003 bcd 沈阳
    004 bcd 大连
    005,006 cdf 大连
    */
      

  3.   

    今天有好几个网友问这个问题SELECT a = STUFF(
    (SELECT ','+[a],t2.[name],t2.c FROM [Table_3] t1
    WHERE t1.[name]=t2.[name] AND t1.[c] =t2.[a] ORDER BY t1.a DESC FOR XML PATH('')),1,1,'')
    FROM [Table_3] t2 GROUP BY t2.[name],t2.[c]楼主可以去看看下面这个帖子
    http://bbs.csdn.net/topics/390565330