不使用ROW_NUMBER() OVER函数获取分区内一行的序号(rank)



我需要按分区(或组)对行进行排序,即,如果我的源表是:

NAME PRICE
---- -----
AAA  1.59
AAA  2.00
AAA  0.75
BBB  3.48
BBB  2.19
BBB  0.99
BBB  2.50

我想获得目标表:

RANK NAME PRICE
---- ---- -----
1    AAA  0.75
2    AAA  1.59
3    AAA  2.00
1    BBB  0.99
2    BBB  2.19
3    BBB  2.50
4    BBB  3.48

通常我会使用ROW_NUMBER() OVER函数,所以在Apache Hive中它将是:

select
  row_number() over (partition by NAME order by PRICE) as RANK,
  NAME,
  PRICE
from
  MY_TABLE
;

不幸的是,Cloudera Impala不支持(目前)ROW_NUMBER() OVER功能,所以我正在寻找一个解决方案。最好不要使用UDAF,因为在政治上很难说服将它部署到服务器上。

如果不能使用相关子查询执行此操作,则仍然可以使用连接执行此操作:

select t1.name, t1.price,
       coalesce(count(t2.name) + 1, 1)
from my_table t1 join
     my_table t2
     on t2.name = t1.name and
        t2.price < t1.price
order by t1.name, t1.price;

注意,除非给定的name的所有价格都不同,否则这并不能完全执行row_number() 。这个公式实际上相当于rank()

对于row_number(),您需要一个唯一的行标识符。

顺便说一下,下面的代码等价于dense_rank():

select t1.name, t1.price,
       coalesce(count(distinct t2.name) + 1, 1)
from my_table t1 join
     my_table t2
     on t2.name = t1.name and
        t2.price < t1.price
order by t1.name, t1.price;

对于不支持窗口函数的系统,通常的解决方法是这样的:

select name, 
       price,
       (select count(*) 
        from my_table t2 
        where t2.name = t1.name  -- this is the "partition by" replacement
        and t2.price < t1.price) as row_number
from my_table t1
order by name, price;

SQLFiddle示例:http://sqlfiddle.com/#!2/3b027/2

不是关于如何使用Impala的答案,但是Hadoop上已经有其他SQL解决方案提供了分析和子查询选项。如果没有这些功能,您可能将不得不依赖多步骤过程或一些UDAF。

我是InfiniDB的架构师
InfiniDB支持分析函数和子查询。
http://infinidb.co

查看Radiant Advisors的基准查询8,这是一个类似风格的查询,您正在使用排名分析功能。Presto也能够运行这种样式查询,只是速度较慢(80倍)http://radiantadvisors.com/wp-content/uploads/2014/04/RadiantAdvisors_Benchmark_SQL-on-Hadoop_2014Q1.pdf

来自基准测试(查询8)的查询

SELECT
    sub.visit_entry_idaction_url,
    sub.name,
    lv.referer_url,
    sum(visit_ total_time) total_time,
    count(sub.idvisit),
    RANK () OVER (PARTITION BY sub. visit_entry_idaction_url
ORDER BY
    count(sub.idvisit)) rank_by_visits,
    DENSE_RANK() OVER (PARTITION BY sub.visit_entry_idaction_url
ORDER BY
    count(visit_total_time)) rank_by_ time_spent
FROM
    log_visit lv,
    (
SELECT
    visit_entry_idaction_url,
    name,
    idvisit
FROM
    log_visit JOIN log_ action
        ON
        (visit_entry_idaction_url = log_action.idaction)
WHERE
    visit_ entry_idaction_url between 2301400 AND
    2302400) sub
WHERE
    lv.idvisit = sub.idvisit
GROUP BY
    1, 2, 3
ORDER BY
    1, 6, 7;
结果

Hive 0.12       Not Executable  
Presto 0.57     506.84s  
InfiniDB 4.0    6.37s  
Impala 1.2      Not Executable  

最新更新