[英]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.