2011-06-19 30 views
1

我已经发现了这个有趣的线程删除重复和排序结果模拟GROUP_CONCAT

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

use test 
go 
create table methods (
id int identity, 
id_exam int, 
method int 
) 
go 
insert into methods (id_exam,method) values (1,5) 
insert into methods (id_exam,method) values (1,2) 
insert into methods (id_exam,method) values (1,5) 
insert into methods (id_exam,method) values (2,1) 
insert into methods (id_exam,method) values (3,5) 
insert into methods (id_exam,method) values (3,2) 
insert into methods (id_exam,method) values (3,2) 
insert into methods (id_exam,method) values (4,5) 
insert into methods (id_exam,method) values (4,3) 

select 
id_exam, 
method = replace ((select method AS [data()] 
        from methods 
        where id_exam = a.id_exam      
        order by id_exam for xml path('')), ' ', ',') 
from methods a 
where id_exam is not null 
group by id_exam 

,让我

1 5,2,5 
2 1 
3 5,2,2 
4 5,3 

但是我想从每个删除重复考试和排序连接结果以获得

1 2,5 
2 1 
3 2,5 
4 3,5 

谢谢。

回答

4

尝试在内部查询中使用DISTINCT,并使用方法而不是id_exam进行排序。

select 
id_exam, 
method = replace ((select distinct method AS [data()] 
        from methods 
        where id_exam = a.id_exam      
        order by method for xml path('')), ' ', ',') 
from methods a 
where id_exam is not null 
group by id_exam 
+0

非常感谢你。它效果很好。 :) –

1

添加group by method到内查询和更改order by id_examorder by method

select 
id_exam, 
method = replace ((select method AS [data()] 
        from methods 
        where id_exam = a.id_exam 
        group by method      
        order by method for xml path('')), ' ', ',') 
from methods a 
where id_exam is not null 
group by id_exam 

结果:

id_exam  method 
----------- --------- 
1   2,5 
2   1 
3   2,5 
4   3,5 
+0

+1。甚至感谢你:) –