1

I've already found this interesting thread

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

that gives me

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

However I'd like to remove duplicates from each exam and sorting the concatenated results in order to get

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

Thanks.

Community
  • 1
  • 1
Nicola Cossu
  • 54,599
  • 15
  • 92
  • 98

2 Answers2

4

Try using DISTINCT in the inner query and ordering by method instead of 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
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

Add a group by method to the inner query and change order by id_exam to order 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

Result:

id_exam     method
----------- ---------
1           2,5
2           1
3           2,5
4           3,5
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281