首页 > 解决方案 > Hive SQL 排名与关系

问题描述

如何在Hive SQL 中重新编写以下查询

select * from sales order by unit_price fetch with ties

标签: sqloraclehivehiveqlranking-functions

解决方案


Oracle 的 ORDER BY .. FETCH NEXT N ROWS WITH TIRES 用于限制返回的 top N(使用 ORDER BY)行数为 NEXT(FIRST)指定的数量。而轮胎意味着如果某些行具有相同的值顺序,除了指定的行数之外,它们也将被返回。

Hive 没有 FETCH 功能。有LIMIT,不支持WITH TIRES。

您可以使用分析 dense_rank() 函数加上 WHERE 过滤器来实现类似的功能。例如,我们需要获取 5 个最低价格的销售,如果有相同价格的销售,也返回它们。dense_rank 将为具有相同价格的行分配相同的排名。

select * 
from
(
    select s.*, 
           dense_rank() over(order by unit_price) rnk --lowest unit_price first
                                                      --to get highest price, use order by unit_price DESC
     from sales s 
) 
where rnk<=5  --If there are rows with the same rank, they all will be returned
order by rnk

推荐阅读