Bla*_*son 2 postgresql ruby-on-rails
我需要按“最近的 A 列,回退到 B 列”对 postgres 表进行排序
如果我的表是这样的:id, reminder_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
Run Code Online (Sandbox Code Playgroud)
预期的排序输出将是
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
Run Code Online (Sandbox Code Playgroud)
我目前正在使用应用程序代码执行此操作,我更喜欢在 SQL 中执行此操作
例如,如果对于记录 1,remember_at 变为 NULL,那么它会立即转到顶部,因为updated_at日期是最旧的
目前:
SELECT *
FROM "tasks"
WHERE completed_at IS NULL
ORDER by reminder_at, updated_at
Run Code Online (Sandbox Code Playgroud)
使用正确答案编辑:
SELECT *
FROM "tasks"
WHERE completed_at IS NULL
ORDER by COALESCE(reminder_at, updated_at)
Run Code Online (Sandbox Code Playgroud)
使用聚结。它选择第一个非空值。
select * from tab
order by coalesce(col1, col2)
Run Code Online (Sandbox Code Playgroud)
如果相反,您想使用 2 个日期中较大的一个。然后使用 best()
select * from tab
order by greatest(col1, col2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |