sql - PostgreSQL - 条件排序

标签 sql postgresql sorting 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

我想要以下排序:

  • 首先,所有带有 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/

相关文章:

sql - Oracle 求和以前的值

mysql - 如何将两个选择结果合并为列

mysql - php排序比mysql "order by"好吗?

algorithm - 在高效的数据结构中存储一桶数字

php - 来自 SQL 的 Laravel Eloquent ORM 聚合函数

sql - 在 Postgres 中将表原始分成 block

sql - 汇总连续的日期范围

c# - 是否有 .net 驱动程序支持与 PostgreSQL 完全验证的 SSL 连接?

python - 按两个字段对 Python 列表进行排序

sql - MS SQL 如何根据最旧日期查询金额