首页 > 解决方案 > Hive 查询以从最新分区中选择行

问题描述

我在蜂巢中有一个分区表。架构和示例如下所示

item_id | price | brand | partition_id
AX_12      340.22  Apple.    356
AZ_47      230.00  Samsung   357
AX_12      321.00. Apple.    357
AQ_17.     125.00  Lenovo.   356

如果一个项目存在于多个分区中。我需要选择具有最新分区的行所以这个例子的预期输出是这样的

item_id | price | brand | partition_id
AX_12      321.00  Apple.    357
AZ_47      230.00  Samsung   357
AQ_17.     125.00  Lenovo.   356

表中有10个分区,每个分区有1000万行

标签: hiveapache-spark-sqlhiveqlgreatest-n-per-group

解决方案


您可以使用窗口函数来过滤每组的顶部记录:

select t.*
from (
    select t.*, row_number() over(partition by item_id order by partition_id desc) rn 
    from mytable t
)
where rn = 1

一个典型的替代方法是使用相关子查询进行过滤:

select t.*
from mytable t
where t.partition_id = (
    select max(t1.partition_id) from mytbale t1 where t1.item_id = t.item_id
)

推荐阅读