我如何按国家/地区分组获得最高薪水

时间:2016-04-20 07:01:47

标签: sql aggregate-functions

------------------------------------------------
country |   salary  |   name    |   adress  
------------------------------------------------
India   |   10000   |   ch1     |   something
japan   |   20000   |   ch2     |   nothing
india   |   25000   |   ch3     |   hjsdj
japan   |   30000   |   ch4     |   hjhjhj

我需要在日本和印度获得最高工资,名字。

2 个答案:

答案 0 :(得分:4)

有一个子查询,返回每个国家/地区的最高工资。加入该结果以获得具有该最高薪水的用户。

select t1.*
from tablename t1
join (select country, max(salary) as max_salary
      from tablename group by country) t2
  on t1.country = t2.country and t1.salary = t2.max_salary

如果两个用户都有平局(即多个具有相同最高薪水的用户),则会返回这两个用户。

答案 1 :(得分:0)

如果您的DBMS偶然支持ROW_NUMBER()OVER()函数,您可以尝试

select * from
  (select ROW_NUMBER() OVER(PARTITION BY country ORDER BY salary DESC) as rn
    , country, salary as max_salary, name, adress
  from tablename
  ) t
where rn = 1  

请注意,与jarlh的查询相反,它将仅为该国家返回一行相同的顶级薪水行。

相关问题