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

如何将数据库中同一列的字符串都连接起来
如何将数据库中同一列的字符串都连接起来?数值的话 可以用sum但是字符串的话没有现成的吧?

------解决方案--------------------
这样?

create table ym 
(col1 int, col2 int, col3 varchar(3)) 
  
insert into ym 
select 1, 1, 'A' union all
select 1, 1, 'B' union all
select 1, 2, 'C' union all
select 1, 3, 'D' union all
select 1, 3, 'E'
  
  
select a.col1,a.col2, 
stuff((select ','+col3 from ym b  
       where b.col1=a.col1 and b.col2=a.col2  
       for xml path('')),1,1,'') 'col3'
from ym a 
group by  a.col1,a.col2

/*
col1        col2        col3
----------- ----------- ----------------------------------------------------------------------------------------------------------------
1           1           A,B
1           2           C
1           3           D,E

(3 行受影响)

*/