如何找到蜂巢中每个组的最新记录

how to find most recent records for every group in hive

这是我的蜂巢table

       id                    name                   starttime(datatype string )

    0000031               workflows_status       Thu, 18 Feb 2016 14:21:38 GMT  
    0000030               workflows_status       Thu, 18 Feb 2016 14:16:28 GMT  
    0000029               workflows_status       Thu, 18 Feb 2016 14:07:25 GMT  
    0000336               hive_test              Tue, 16 Feb 2016 09:27:54 GMT  
    0000335               hive_test              Tue, 16 Feb 2016 09:17:52 GMT  
    0000334               hive_test              Tue, 16 Feb 2016 09:00:26 GMT

我希望配置单元查询得到以下结果

    id               name                   starttime

    0000031          workflow_status        Thu, 18 Feb 2016 14:21:38 GMT
    0000336          hive_test              Tue, 16 Feb 2016 09:27:54 GMT             

您可以使用以下查询获得所需的输出:

select * from (select id, name, starttime, rank() over(partition by name order by unix_timestamp(starttime, 'EEE, dd MMM yyyy hh:mm:ss z') desc) as rnk from hive_table) a where a.rnk=1;

Hive 允许通过 Windowing and Analytics Functions 进行此类操作。

使用 RANK() 函数和 OVER 子句,你可以达到你想要的结果。 Over 子句将按指定列名的结果分组,然后 Rank = 1 将在每个组中获得第一个结果。这类似于 oracle 中的 ROWNUM = 1

select * from (
 select 
   id, 
   name, 
   starttime, 
   rank() over ( partition by name order by starttime) desc ) as rank_alias 
 from hive_table
) a where a.rank_alias = 1;