简体   繁体   English

Postgres条件/混合排序

[英]Postgres conditional / mixed sorting

I have a table with a timestamp column, something like this: 我有一个带有时间戳列的表,如下所示:

╔═══════╦════════════╦
║ name  ║ date_time  ║ 
╠═══════╬════════════╬
║  A    ║     100    ║
║  B    ║     110    ║
║  C    ║     120    ║
║  D    ║     140    ║
║  E    ║     180    ║
║  F    ║     190    ║
╚═══════╩════════════╩

I need to return the records so that the records come in two groups, the records where date_time is in the future are the first group, and the records where date_time is in the past are the second group. 我需要返回记录,以使记录分为两类,date_time在将来的记录是第一组,而date_time在过去的记录是第二组。 The records in the future need to be sorted in ascending order(ie the closest to now comes first), and the records in the past need to be sorted in descending order. 将来的记录需要按升序排序(即最接近现在的记录排在第一位),而过去的记录则需要按降序排序。

I managed to solve this by making two separate queries and joining the results with union all, but this is not very performant and I was curious to know if there was any better approach? 我设法通过进行两个单独的查询并将结果与​​union all合并在一起来解决此问题,但这并不是很有效,我很好奇是否有更好的方法? Maybe by using a conditional sorting on the order by? 也许通过对订单使用条件排序?

In Postgres you can sort booleans - false values come before true values. 在Postgres中,您可以对布尔值进行排序- false值先于true值。 So you can sort according to two expressions - a condition that checks if a record is in the past or future, and the absolute distance of it from the current timestamp: 因此,您可以根据两个表达式进行排序-检查记录是过去还是将来的条件,以及它与当前时间戳的绝对距离:

SELECT *
FROM   mytable
ORDER BY date_time < CURRENT_TIMESTAMP, 
         ABS(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) -
             EXTRACT(EPOCH FROM date_time))

I would do this using three sort keys: 我将使用三个排序键来执行此操作:

order by (date_time < current_timestamp),
         (case when date_time < current_timestamp then date_time end) desc,
         date_time asc;

Here is a rextester. 是一个学期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM