我正在使用Postgresql 10,并尝试对我的选择查询进行排序,以使我拥有的两个日期列之间的较小日期排在最前面。
这里是sqlfiddle
排序结果将如下所示:
+----+--------------+--------------+
| id | column1_date | column2_date |
+----+--------------+--------------+
| 1 | 2018-05-07 | null |
+----+--------------+--------------+
| 3 | null | 2018-05-28 |
+----+--------------+--------------+
| 2 | 2018-06-28 | 2018-06-30 |
+----+--------------+--------------+
| 4 | null | 2018-07-12 |
+----+--------------+--------------+
我试图这样做:
SELECT * FROM Test
ORDER BY
CASE WHEN column1_date is null AND column2_date is not null
THEN column2_date END ASC, column1_date ASC,
CASE WHEN column1_date is not null AND column2_date is null
THEN column1_date END ASC, column2_date ASC,
CASE WHEN column1_date is not null AND column2_date is not null AND column1_date < column2_date
THEN column1_date END ASC, column2_date ASC,
CASE WHEN column1_date is not null AND column2_date is not null AND column1_date > column2_date
THEN column2_date END ASC, column1_date ASC
但这并不成功。 我想念什么?
谢谢
答案 0 :(得分:4)
您可以使用
ORDER BY least(coalesce(column1_date, DATE 'infinity'),
coalesce(column2_date, DATE 'infinity'))
这将始终使用两者中较小的一个。
如果两列均为NULL,则该行将排在最后。
答案 1 :(得分:0)
您可以使用内部子查询:
select
t.id, t.column1_date, t.column2_date
from (
select
id,
column1_date,
column2_date,
CASE
WHEN column1_date is null then column2_date
WHEN column2_date is null then column1_date
WHEN column1_date < column2_date THEN column1_date
ELSE column2_date
END AS min_date
from Test) as t
order by t.min_date;