从单独的表中获取最高工资 getter 和 his/her 部门

Getting the maximum salary getter and his/her department from separate tables

我被要求解决以下问题。

我试过的:

  1. 我想将所有三个表连接在一起。但是我在获得每个部门的最高薪水方面面临挑战。
select e.empName, d.deptName
from employee e
  join department d on e.deptId = d.deptId
  join salary s on e.empId = s.EmpId
where s.salary = (select max(salary) from salary s)
group by d.deptid;

我也参考了这些答案,但我无法根据需要实施它们。

  1. join-multiple-columns-from-one-table-to-single-column-from-another-table
  2. sql-select-only-rows-with-max-value-on-a-column
  3. select-emp-with-max-sal-from-each-dept

这是我的sqlfiddlelink。我正在使用 MYSQL 版本 5.6 SQL FIDDLE

任何建议都会有所帮助。

您可以使用 rank():

select *
from (
    select e.empName, d.deptName, s.salary, 
        rank() over(partition by d.deptId order by s.salary desc) rn
    from employee e 
    join department d on e.deptId = d.deptId
    join salary s on e.empId = s.EmpId
) t
where rn = 1

这需要 MySQL 8.0。在 MySQL 的早期版本中,您将使用相关子查询:

select e.empName, d.deptName, s.salary
from employee e 
join department d on e.deptId = d.deptId
join salary s on e.empId = s.EmpId
where s.salary = (
    select max(s1.salary)
    from salary s1
    join employee e1 on e1.empId = s1.empId
    where e1.deptId = d.deptId
)

这是使用window 函数的好地方:

select empName, deptName
from (select e.empName, d.deptName, s.salary,
             max(s.salary) over (partition by d.deptName) as max_salary
      from employee e join
           department d
           on e.deptId = d.deptId join
           salary s
           on e.empId = s.EmpId 
     ) ed
where salary = max_salary;

Here 是一个 db<>fiddle.

select *
from (
    select *,
       ROW_NUMBER() OVER (PARTITION BY d.deptId ORDER BY s.salary DESC) rn
    from employee e 
    join department d on e.deptId = d.deptId
    join salary s on e.empId = s.EmpId
) tbl
where rn = 1