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

合并多列

Create table aaa(ID int,ch char(1))
insert into aaa values(1,'a')
insert into aaa values(1,'b')
insert into aaa values(2,'x')
insert into aaa values(2,'y')
insert into aaa values(2,'z')
--sql语句不会写,想要的结果是这样的,请各位大师帮忙,Thanks
print '1 ab'
print '2 xyz'

------解决方案--------------------
不知道是不是你要的那个格式

select a.id,
stuff((select ' '+ch from aaa b 
       where b.id=a.id 
       for xml path('')),1,1,'') 'ch'
from aaa a
group by  a.id

------解决方案--------------------
写个follow迭代的。


drop table aaa
go
Create table aaa(ID int,ch char(1))
insert into aaa values(1,'a')
insert into aaa values(1,'b')
insert into aaa values(2,'x')
insert into aaa values(2,'y')
insert into aaa values(2,'z')
go
select distinct id,stuff(v,1,1,'') from aaa c
cross apply
(
select x=(select * from aaa where id=c.id for xml path('r'),type)
)a
CROSS APPLY
    (SELECT v=CAST(a.x.query('for $r in //r  return concat(",",xs:string($r/ch[1]))') AS VARCHAR(MAX))) b
 


更多写法,可参考我以前写的

http://bbs.csdn.net/topics/280055586
------解决方案--------------------
小妹妹下班了哦
------解决方案--------------------

------解决方案--------------------
select distinct id,
(select ''+ch from test where id=a.id for xml path(''))
 from test a

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

if OBJECT_ID('aaa') is not null
drop table aaa
if OBJECT_ID('combin') is not null
drop function combin
go
Create table aaa(ID int,ch char(1))
insert into aaa values(1,'a')
insert into aaa values(1,'b')
insert into aaa values(2,'x')
insert into aaa values(2,'y')
insert into aaa values(2,'z')
go
create function combin(@id int)
returns varchar(10)
as begin
declare @val varchar(10)=''
select @val=@val+ch from aaa where id=@id
return @val
end
go
select id,dbo.combin(id) from aaa group by ID