【问题标题】:Removing duplicates and sort results emulating group_concat删除重复项并模拟 group_concat 对结果进行排序
【发布时间】:2011-09-18 03:32:55
【问题描述】:

我已经找到了这个有趣的话题

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

谢谢。

【问题讨论】:

    标签: sql-server-2005 tsql sorting duplicates group-concat


    【解决方案1】:

    尝试在内部查询中使用 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
    

    【讨论】:

      【解决方案2】:

      group by method 添加到内部查询并将order by id_exam 更改为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
      

      结果:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-18
        • 2013-12-03
        • 2014-04-29
        • 2017-10-09
        • 2021-11-20
        • 2016-03-12
        • 2013-05-02
        • 2014-11-05
        相关资源
        最近更新 更多