日期:2014-05-17 浏览次数:20563 次
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
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
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