2013-10-22 61 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