编写sql&hive查询以打印每个国家支付第二高工资的年份?

bjg7j2ky  于 2021-06-25  发布在  Hive
关注(0)|答案(2)|浏览(221)

编写sql和配置单元查询以打印每个国家/地区支付第二高工资的年份?。
请提供下表查询

country,salary,year
india,1000,2017
japan,2000,2017
germany,1500,2017
india,1250,2018
japan,500,2018
china,955,2017
japan,850,2019
china,1150,2018
india,1250,2019
euoag5mw

euoag5mw1#

最大的问题是如何处理领带。你大概是说第二高的薪水吧。在这种情况下,你是专门寻找 dense_rank() 窗口功能:

select t.*
from (select t.*,
             dense_rank() over (partition by country order by salary desc) as seqnum
      from t
     ) t
where t.seqnum = 2;

现在,这样做的挑战是,如果出现平局,它可能会返回多行。如果您特别想要一行,那么:

select t.*
from (select t.*,
             dense_rank() over (partition by country order by salary desc) as ranking,
             row_number() over (partition by country, salary order by country) as seqnum
      from t
     ) t
where t.ranking = 2 and seqnum = 1;
7cwmlq89

7cwmlq892#

比如:

select 
    t.*
from (
    select
        tbl.*,
        row_number() over(partition by country order by salary desc) rn
    from 
        tbl
) t
where 
    t.rn = 2

相关问题