日期:2014-05-17  浏览次数:20506 次

求一条组合字符串的sql
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字段都相同,则合并用逗号分隔



------解决方案--------------------

;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 沈阳
*/

------解决方案--------------------
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