我有以下查询:
select id, table1.date1, table2.date2, table1.name
from table1
join table2 using (id)
我也想在MAX(table1.date1, table2.date2)
中添加另一列,但是我没有找到合适的语法。我不希望MAX遍历表中的所有行并采用MAX(),我希望它从行中指定的两个值中选择max。
示例:
id date1 date2 name max
1 2020-01-01 2020-04-01 A 2020-04-01
2 2019-02-01 2020-01-03 B 2020-01-03
3 2019-02-01 null c 2019-02-01
我也不能分组,因为我不想在这里分组。它更类似于coalesce
给出值的函数列表并从中选择最大值
您可以尝试
select id, table1.date1, table2.date2, table1.name,
case when table1.date1 > table1.date2 then table1.date1 else table1.date2 end as max_date
from table1
join table2 using (id)