如何在 presto 中取两个值之间的最大值?
How to take max between two values in presto?
我有以下查询:
select id, table1.date1, table2.date2, table1.name
from table1
join table2 using (id)
我还想有另一个包含 MAX(table1.date1, table2.date2)
的专栏,但我找不到合适的语法。我不希望 MAX 遍历 table 中的所有行并取 MAX() 我希望它从行中指定的两个值中达到 select 最大值。
示例:
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)
使用greatest()
:
select id, t1.date1, t2.date2, t1.name,
greatest(t1.date1, t2.date2)
from table1 t1 join
table2 t2
using (id);
请注意,如果任何参数为 NULL
,则 greatest()
returns NULL
。因此,如果您有 NULL
个值,则需要特别小心。
我有以下查询:
select id, table1.date1, table2.date2, table1.name
from table1
join table2 using (id)
我还想有另一个包含 MAX(table1.date1, table2.date2)
的专栏,但我找不到合适的语法。我不希望 MAX 遍历 table 中的所有行并取 MAX() 我希望它从行中指定的两个值中达到 select 最大值。
示例:
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)
使用greatest()
:
select id, t1.date1, t2.date2, t1.name,
greatest(t1.date1, t2.date2)
from table1 t1 join
table2 t2
using (id);
请注意,如果任何参数为 NULL
,则 greatest()
returns NULL
。因此,如果您有 NULL
个值,则需要特别小心。