繁体   English   中英

查询排序顺序问题

[英]Query Sort Order Issue

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

查询1:

 Corporate Comp D
 Corporate Comp E

查询2:

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

因此,在合并后,结果为ABDE G.及其按字母顺序排列的顺序,但是,我希望通过第一个查询对其进行排序,所以基本上我希望该顺序像

最终排序查询

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

在这种情况下,请勿使用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;

您可以尝试以下方法:

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
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      
 ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM