1

私はすでにこの興味深いスレッドを見つけました

Microsoft SQL Server 2005 で group_concat MySQL 関数をシミュレートしていますか?

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

2 に答える 2

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
于 2011-06-19T12:50:01.427 に答える
1

group by method内部クエリにaを追加し、に変更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
于 2011-06-19T13:00:08.223 に答える