2011-06-19 27 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。甚至感謝你:) –