每个国家/地区员工薪资的最高价值

时间:2016-07-12 17:40:23

标签: sql postgresql select greatest-n-per-group

这是我的数据库:

  • 表国家/地区:id整数(pk),varchar名称,
  • 表Employe:id integer(pk),countryid integer(fk),varchar name,integer salary。

我想展示每个国家薪水最高的员工,但我只能展示一个薪水最高的雇主。

这是我的SQL查询:

Select * 
from Employe 
order by Employe.salary 
desc LIMIT 1;

3 个答案:

答案 0 :(得分:2)

在Postgres中,您可以使用舒适的distinct on

select distinct on (c.name) c.name country, e.name employe, salary
from employe e
join countries c on c.id = e.country_id
order by c.name, salary desc

答案 1 :(得分:1)

尝试此查询

SELECT Employe.countryid , Max(Employe.salary) from Employe GROUP BY  Employe.countryid 

答案 2 :(得分:1)

你可以使用rank窗口函数来获得"第一个"员工[s](按工资计算)每个国家:

SELECT id, c.name, e.name, salary
FROM   (SELECT id, countryid, name, salary, 
               RANK() OVER (PARTITION BY countryid ORDER BY salary DESC) rk
        FROM   employee) e
JOIN   country c ON c.id = e.countryid
WHERE  rk = 1