2016-11-07 81 views
0

我有兩個查詢,我進一步做一個聯合來獲得不同的結果。目前,它們按名稱按字母順序排序。查詢排序順序問題

查詢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 
01工作
+0

(1)什麼數據庫您使用的? (2)每個查詢中是否有重複項? –

+0

是的,可以有重複的,使用SQL Server – user2675939

回答

2

在這種情況下,請勿使用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; 
0

你可以試試這個: -

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