PostgreSQL按两个日期中最早的日期排序?

时间:2019-01-11 19:20:35

标签: ruby-on-rails postgresql

我需要按“列A的最新版本,后退到列B”对postgres表进行排序

如果我的表格是这样的:css-loaderidreminder_at

updated_at

预期的排序输出为

1, 01-11-2019, 12-01-2018
2, null,       01-04-2019
3, null,       01-02-2019
4, 01-01-2019, 01-04-2019

我目前正在使用应用程序代码来执行此操作,并且我更喜欢使用SQL

例如,如果对于记录1,inherert_at变为NULL,则它会立即到达顶部,因为4, 01-01-2019, 01-04-2019 # 01-01-2019 is soonest 3, null, 01-02-2019 # then 01-02-2019 2, null, 01-04-2019 # then 01-04-2019 1, 01-11-2019, 12-01-2018 # then 01-11-2019 日期是最早的

当前:

updated_at

编辑并给出正确答案:

SELECT * 
FROM "tasks" 
WHERE completed_at IS NULL
ORDER by reminder_at, updated_at

2 个答案:

答案 0 :(得分:2)

使用合并。它选择第一个非null值。

 select * from tab
 order by coalesce(col1, col2)

如果相反,您想使用2个日期中的较大者。然后使用great()

 select * from tab
 order by greatest(col1, col2)

答案 1 :(得分:0)

我将您的数据格式解释为mm-dd。应该在输出中翻转3和2,第二个在第四个之后?

以下工作吗?

从测试顺序中选择id,reminder_at,updated_at,greatest(coalesce(reminder_at,'1/1/1900'),coalesce(updated_at,'1/1/1900'))作为测试列,按最大(coalesce(reminder_at, '1/1/1900'),coalesce(updated_at,'1/1/1900'));

相关问题