以毫秒连接列的配置单元

ubbxdtey  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(383)

我有一个表,表中有id、create、time和code列。create\u time列的类型为string,其时间戳值的格式为yyyy-mm-dd hh:mm:ss.ssssss现在我的要求是为每个id查找最新代码(最近的create\u time)。如果create\u time列没有毫秒部分,我可以这样做

select id,create_time,code from(
select id,max(unix_timestamp(create_time,"yyyy-MM-dd HH:mm:ss")) over (partition by id) as latest_time from table)a
join table b on a.latest_time=b.create_time

由于unix时间函数只考虑秒而不是毫秒,因此我无法继续使用它们。
请帮忙

jgovgodb

jgovgodb1#

你为什么要改变信仰?因为您只需要查找最新的时间戳,所以我只需执行以下操作:

select id,create_time,code from(
select id,max(create_time) over (partition by id) as latest_time from table)a
join table b on a.latest_time=b.create_time

那些没有毫秒的将被处理,因为他们将有“000000”代替。

pprl5pva

pprl5pva2#

你不需要加入。
如果您需要max(create\u time)的所有记录,请使用rank()或dense\u rank()。如果有多个记录的创建时间相同,则rank将为所有具有最新创建时间的记录分配1。
如果每个id只需要一个记录,即使有许多create\u time=max(create\u time)的记录,也可以使用 row_number() 而不是 rank() :

select id,create_time,code 
from
(
select id,create_time,code,
       rank() over(partition by id order by create_time desc) rn
)s
where rn=1;

相关问题