[英]Write SQL & Hive query to print the year in which the 2nd highest salary was paid for each country?
编写 SQL 和 HIVE 查询以打印每个国家支付第二高工资的年份?。
请提供下表的查询
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
就像是:
select
t.*
from (
select
tbl.*,
row_number() over(partition by country order by salary desc) rn
from
tbl
) t
where
t.rn = 2
最大的问题是你如何处理关系。 据推测,您的意思是第二高的不同工资。 在这种情况下,您是专门寻找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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.