Hive 正在查找组、配置单元中的前n个匹配项

Hive 正在查找组、配置单元中的前n个匹配项,hive,hiveql,top-n,Hive,Hiveql,Top N,我有一个表,其中每条记录都有列:标题和类别。 我想找到两个在他们的类别中出现最多的标题。有些标题列在这两个类别中。如何在蜂箱中实现这一点 下面是一个表创建查询: create table book(category String, title String) row format delimited fields terminated by '\t' stored as textfile; 和示例数据: fiction book1 fiction book2 fiction book3 fic

我有一个表,其中每条记录都有列:标题和类别。 我想找到两个在他们的类别中出现最多的标题。有些标题列在这两个类别中。如何在蜂箱中实现这一点

下面是一个表创建查询:

create table book(category String, title String) row format delimited fields terminated by '\t' stored as textfile;
和示例数据:

fiction book1
fiction book2
fiction book3
fiction book4
fiction book5
fiction book6
fiction book7
fiction book8
fiction book8
fiction book8
psychology  book1
psychology  book2
psychology  book2
psychology  book2
psychology  book2
psychology  book7
psychology  book7
psychology  book7
预期结果:

fiction book8
fiction any other
psychology  book2
psychology  book7
目前,我已成功编写了以下查询:

SELECT * FROM  
(SELECT category, title,
             count(*) as sale_count
             from book
             Group BY category, title) a 
order by category, sale_count DESC; 

这为每个类别中的一个标题提供了计数,但我找不到从每个类别中只返回两条顶级记录的方法,因为只有两条顶级记录使用了行编号

select category, title, sale_count
from
(
SELECT a.*,
row_number() over(partition by category order by sale_count desc) rn
 FROM  
(SELECT category, title,
             count(*) as sale_count
             from book
             Group BY category, title) a 
)s where rn <=2

order by category, sale_count DESC; 

如果有多行具有相同的最高销售额,并且您需要返回两个最高销售额的所有最高销售额行,请使用密集排名而不是行编号,如果有具有相同销售额的标题,它将分配相同的排名。

请提供具有代表性的数据示例和所需的输出。@leftjoin添加了示例数据和预期结果