2017-04-10 48 views
1

我有如下表:PostgreSQL的 - 有條件訂貨

key | date   | flag 
-------------------------- 
1 now()   true 
2 now() - 1 hour true 
3 now() + 1 hour true 
4 now()   false 
5 now() - 1 hour false 
6 now() + 1 hour false 

我想以下分類:

  • 首先,所有flag = false行。這些行必須按date asc排序。
  • 然後,所有其他行(flag = true)。但是,這些行必須按date desc排序。

是下面的查詢是否正確?

(
    select * 
    from test 
    where flag = false 
    order by date asc 
) 
union all 
(
    select * 
    from test 
    where flag = true 
    order by date desc 
) 

有沒有更好的方法來做到這一點?請問union all保持行排序的,因此只是將兩者連接起來的內層查詢的輸出?

我不知道如何重複列在order by,根據條件。

更新

小提琴可以在這裏找到:http://rextester.com/FFOSS79584

+0

條件排序與'CASE' –

+0

像水木清華做'爲了通過標誌情況下,當標誌然後日期端遞減,情況下,當未標記然後日期端asc' http://rextester.com/FDAY76293 –

回答

2

有條件的順序可以與CASE進行,喜歡這裏:

select * 
    from test 
order by 
    flag 
    , case when flag then date end desc 
    , case when not flag then date end asc