ruby-on-rails - PostgreSQL 按两个日期中最旧的日期排序?

标签 ruby-on-rails postgresql

我需要按“A 列的更新,回退到 B 列”对 postgres 表进行排序

如果我的表格如下所示:idreminder_atupdated_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

预期的排序输出将是

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

我目前正在用应用程序代码来做这件事,我更喜欢用 SQL 来做

例如,如果记录 1 的 reminder_at 变为 NULL,那么它会立即转到顶部,因为 updated_at 日期是最早的

目前:

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

编辑正确答案:

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

最佳答案

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

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

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

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

关于ruby-on-rails - PostgreSQL 按两个日期中最旧的日期排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54152773/

相关文章:

sql - 从非阻塞用户获取帖子

ruby-on-rails - ROR 的登录/注销流程(Rails 3.2.2)

ruby-on-rails - Paginate 使用逗号 gem 限制我的 csv 导出 - 如何解决?

php - Ruby 命令未在 PHP shell_exec 函数中执行

ruby-on-rails - Rails,通过自定义的唯一字段引用关联

Spring 数据 jpa : Not an managed type: class xxx

postgresql - 如何使用 postgres 数据库,就好像它是 Rails 原生的一样

php - 从具有 10k+ 记录的表中选择随机行

ruby-on-rails - 在 Rails 上使用react - ! [远程拒绝] master -> master(预接收 Hook 被拒绝)

SQL - 如何使用 sql 对一个查询的输出进行分组?