PostgreSQL - 条件排序

Cli*_* T. 2 sql sorting postgresql sql-order-by

我有下表:

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
Run Code Online (Sandbox Code Playgroud)

我想要以下排序:

  • 首先,所有行都有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
)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?将union all保持行排序的,因此只是将两者连接起来的内层查询的输出?

order by根据条件不知道如何重复列中的列.

更新

小提琴可以在这里找到:http://rextester.com/FFOSS79584

Vao*_*sun 9

条件订单可以执行CASE,如下所示:

select *
    from test
order by 
    flag
  , case when flag then date end desc
  , case when not flag then date end asc
Run Code Online (Sandbox Code Playgroud)