postgresql - 何时获取两列之间的最大时间戳的情况

postgresql - case when to get the max timestamp between two columns

我想要 return 最大 updated_date 时间戳。我有这个代码:

select 
case when max(t1.updated_date) > max(t2.updated_date)
then t1.updated_date else t2.updated_date
end as MaxDate
from table1 t1
inner join table2 t2
on t1.id = t2.id 
where t1.id = '5'
group by t1.updated_date, t2.updated_date 

当我 运行 这段代码时,我的结果集是 t1 和 t2 的最大值 updated_date:

MaxDate
2021-12-10 8:00:00
2021-12-20 23:00:00

为什么 return 两者兼而有之?如何仅在 2021-12-20 23:00:00 将其设置为 return(即比较两列时的最大时间戳)?

我想你只是想在这里查询一个限制。由于 Postgres 支持标量 GREATEST 函数,因此您不需要笨重的 CASE 表达式。考虑这个版本:

SELECT GREATEST(t1.updated_date, t2.updated_date) AS max_updated_date
FROM table1 t1
INNER JOIN table2 t2
    ON t1.id = t2.id 
WHERE t1.id = '5'
ORDER BY 1 DESC
LIMIT 1;