【问题标题】:PostgreSQL - conditional orderingPostgreSQL - 条件排序
【发布时间】:2017-09-05 10:20:42
【问题描述】:

我有下表:

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

【问题讨论】:

  • 条件排序通过CASE完成
  • smth like order by flag,case when flag then date end desc, case when not flag then date end asc rextester.com/FDAY76293

标签: sql postgresql sorting sql-order-by


【解决方案1】:

可以使用CASE 执行条件排序,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多