【问题标题】:Hive: Find top 20 percent recordsHive:查找前 20% 的记录
【发布时间】:2019-02-10 17:31:00
【问题描述】:

我有一些数据,例如:-

ID  PRICE
1   100
2   200
3   120
4   130
5   320
6   300
7   200
8   100
9   120
10  250

我需要找到最高 20% 的价格。

预期输出:-

ID  PRICE
5   320
6   300

【问题讨论】:

  • 请也包括您的尝试。

标签: hadoop hive bigdata hiveql


【解决方案1】:

你可以在没有连接的情况下做到这一点。用解析函数计算max(price),取80%,然后用filter price>80%:

with your_data as ( --this is your data
select stack(10,
1 ,  100,
2 ,  200,
3 ,  120,
4 ,  130,
5 ,  320,
6 ,  300,
7 ,  200,
8 ,  100,
9 ,  120,
10,  250) as (ID,  PRICE)
)

select id, price 
from
(
select d.*, max(price) over()*0.8 as pct_80 from your_data d
)s where price>pct_80

结果:

OK
id      price
6       300
5       320

使用您的表而不是 WITH 子查询,如有必要,按 ID 添加顺序。

【讨论】:

    【解决方案2】:

    下面是查询-

    with top_20 as (
      select 
        max(price)*0.8 as price1 
      from 
        <tableName>
    )
    select * from <tableName> t1 , top_20 t2 where t1.price > t2.price1;
    
    select 
     name, 
     price 
    from 
     (select 
        name, 
        price, 
        max(price)*0.8 over (order by price) as top_20 
     from <tableName>
     ) t1 
    where 
     t1.price > t1.top_20;
    

    以下查询在 hive 中不起作用 -

    select * from <tableName> where price > (select max(salary)*0.8 from <tableName>)
    
    select * from <tableName> t1 where exists (select salary from <tablename> t2 where t1.salary > t2.salary*0.8)
    

    原因 - Hive 不支持条件相等的 where 子句中的子查询,它只支持 IN、NOT IN、EXISTS 和 NOT EXISTS。

    即使有Exists和NOT Exists,它也只支持Equijoin,更多详情请参考https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries#LanguageManualSubQueries-SubqueriesintheWHEREClause

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      这是一种无需使用join 即可完成的方法。

      Select id,price from (select id,price, row_number() over(order by price desc) r1,count(*) over()*(20/100) ct from table_name)final where r1<=ct ;
      

      【讨论】:

        猜你喜欢
        • 2012-11-11
        • 2016-07-15
        • 1970-01-01
        • 2012-03-12
        • 2017-03-20
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多