如何将字符串转换为日期并在 Impala 中使用 MIN 和 MAX?

How to convert string to date and use MIN and MAX in Impala?

我正在尝试获取列中的最高日期和最低日期,从那里获取具有这些相应日期的行的文件大小列中的数据,并将其添加到另一列。 我编写了以下代码,但它不起作用。

CASE WHEN MIN(to_timestamp(extract_dt, 'yyyy-MM-dd')) THEN filesize ELSE 0 END filesize_extracao_passada,

您可以使用如下所示的 SQL。

select 
filesize,dt,
if ( mx.mxdt = to_timestamp(extract_dt, 'yyyy-MM-dd'), filesize,null) mx_dt, -- this compares and display filesize for max dt
if ( mn.mndt = to_timestamp(extract_dt, 'yyyy-MM-dd'), filesize,null) mn_dt
from mytable
left join (select max(to_timestamp(extract_dt, 'yyyy-MM-dd')) mxdt from tmp)mx on 1=1 --This calculates maximum date
left join (select min(to_timestamp(extract_dt, 'yyyy-MM-dd')) mndt from tmp)mn on 1=1 --This calculates minimum date
WHERE 
mn.mndt = to_timestamp(extract_dt, 'yyyy-MM-dd') OR mx.mxdt = to_timestamp(extract_dt, 'yyyy-MM-dd')  -- this ensure your select clause returns only rows having maximum or minimum dates

如果您想在您的环境中试用,这是我的代码。

create table tmp  as 
select 'a' as id, now() dt union all
select 'a' as id, now()+ interval 1 days dt union all
select 'a' as id, now() - interval 5 days dt union all
select 'a' as id, now()+ interval 3 days dt union all
select 'a' as id, now()+ interval 3 days dt union all
select 'a' as id, now()+ interval 1 days dt union all
select 'a' as id, now()+ interval 2 days dt ;

select 
id,dt,
if ( mx.mxdt = dt, id,null) mx_dt,
if ( mn.mndt = dt, id,null) mn_dt
from tmp
left join (select max(dt) mxdt from tmp)mx on 1=1
left join (select min(dt) mndt from tmp)mn on 1=1
WHERE mx.mxdt = dt or mn.mndt = dt