我有下表:
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
中的列。
更新
fiddle 可以在这里找到:http://rextester.com/FFOSS79584
最佳答案
可以使用CASE
执行条件订单,如下所示:
select *
from test
order by
flag
, case when flag then date end desc
, case when not flag then date end asc
关于sql - PostgreSQL - 条件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322046/