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

求sql做法,不同记录同一字段合并字符串
比如有表T
f1       f2
-------------
1        aaa
2        bbb
2        ccc
希望获得
f1        f2
-------------
1         aaa
2         bbbccc

怎样写好?

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

with S as
(
select f1,f2 from 表T group by f1,f2 
)
select t.f1,stuff((select ''+t2.f2 from S t2 where t2.f1 = t.f1 for xml path('')),1,O,'')'f2'
from S t 
group by t.f1

------解决方案--------------------
加个distinct即可,

create table 表T
(f1 int, f2 varchar(10))

insert into 表T
select 1, 'aaa' union all
select 2, 'bbb' union all
select 2, 'ccc' union all
select 2, 'ccc'


select f1,f2 from 表T
/*
f1          f2
----------- ----------
1           aaa
2           bbb
2           ccc
2           ccc

(4 row(s) affected)
*/


select a.f1,
       replace((select distinct '
------解决方案--------------------
'+f2  
        from 表T b
        where b.f1=a.f1
        for xml path('')),'
------解决方案--------------------
','') 'f2'
 from 表T a
 group by a.f1
 
/*
f1          f2
----------- -------------
1           aaa
2           bbbccc

(2 row(s) affected)
*/