【问题标题】:Query Sort Order Issue查询排序顺序问题
【发布时间】:2016-11-07 20:49:06
【问题描述】:

我有两个查询,我进一步对它们进行联合以获得不同的结果。目前,它们按名称按字母顺序排列。

查询 1:

 Corporate Comp D
 Corporate Comp E

查询 2:

 Corporate Comp A
 Corporate Comp B
 Corporate Comp D
 Corporate Comp E
 Corporate Comp G

所以在联合之后,结果是 A B D E G. 并且它按字母顺序排列,但是,我希望它按第一次查询排序,所以基本上我希望顺序像

最终排序查询

 Corporate Comp D
 Corporate Comp E
 Corporate Comp A
 Corporate Comp B
 Corporate Comp G

【问题讨论】:

  • (1) 您使用的是什么数据库? (2) 每个查询中是否可以有重复项?
  • 是的,可以有重复,使用 SQL Server

标签: sql sorting


【解决方案1】:

在这种情况下,不要使用UNION。这是一个替代方案:

select qq.col
from ((select q.col, 1 as which
       from query1 q
      ) union all
      (select q.col, 2 as which
       from query2 q
       where not exists (select 1 from query1 q1 where q1.col = q.col)
      )
     ) qq
order by qq.which, qq.col;

或者,您可以使用聚合:

select qq.col
from ((select q.col, 1 as which
       from query1 q
      ) union all
      (select q.col, 2 as which
       from query2 q
      )
     ) qq
group by qq.col
order by min(qq.which), qq.col;

【讨论】:

    【解决方案2】:

    你可以试试这个:-

    select 
        *
    from 
    (
        select col from query1
        union
        select col from query2
    ) d
    order by 
        case when col in (select col from query1) then 0 else 1 end, 
        col
    

    【讨论】:

      【解决方案3】:
      select      col
      
      from       (          select distinct 1 as i,col from query1
                  union all (select 2,col from query2 minus select 2,col from query1)
                 ) t
      
       order by   i,col      
       ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-07
        • 2014-02-03
        • 2012-03-10
        • 1970-01-01
        • 1970-01-01
        • 2019-06-13
        • 2013-12-22
        • 2021-10-11
        相关资源
        最近更新 更多