2013-10-22 60 views
2
create table [temp](
[id] [nvarchar](10) not null, 
[name] [nvarchar](50) not null, 
[info1] [nvarchar](50) not null, 
[info2] [nvarchar](50) not null, 
[info3] [nvarchar](50) not null); 

insert into temp(id,name,info1,info2,info3) values ('id1','name1','infoa','infob','infoc'); 
insert into temp(id,name,info1,info2,info3) values ('id1','name1','infox','infod','infoc'); 
insert into temp(id,name,info1,info2,info3) values ('id1','name1','infoz','infob','infoc'); 

表看起來遵循從臨時表SQL Server 2008中 - 透視

temp table 
id   name info1  info2  info3 
id1  name1 infoa  infob  infoc 
id1  name1 infox  infod  infoc 
id1  name1 infoy  infob  infoc 

多行將由ID,名稱和所有獨特的信息欄分組將被串聯預期輸出

id name info1    info2   info3 
id1 name1 infoa;infox;infoy infob;infod infoc 
+0

格式輸出正確? –

回答

0
select [id],[name], 
    stuff((select distinct ',' + CAST(t2.[info1] as varchar(10)) 
    from [temp] t2 where t1.id = t2.id and t1.name = t2.name 
    for xml path('')),1,1,'') info1, 
    stuff((select distinct ',' + CAST(t3.[info2] as varchar(10)) 
    from [temp] t3 where t1.id = t3.id and t1.name = t3.name 
    for xml path('')),1,1,'') info2, 
    stuff((select distinct ',' + CAST(t4.[info3] as varchar(10)) 
    from [temp] t4 where t1.id = t4.id and t1.name = t4.name 
    for xml path('')),1,1,'') info3 
from [temp] t1 
group by id,Name 

使用的功能

  1. Stuff
  2. For XML
  3. Group by
+0

謝謝你解決了我的問題。 – user2860891

+0

嗨,我已經接受了答案,提供了謝謝。 – user2860891