【问题标题】:Getting the maximum salary getter and his/her department from separate tables从单独的表中获取最高薪水获取者及其部门
【发布时间】:2021-03-15 12:33:33
【问题描述】:

我得到了以下问题要解决。

我尝试了什么:

  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

这是我的 sql fiddle 链接。我使用的是 MYSQL 5.6 版 SQL FIDDLE

任何建议都会有所帮助。

【问题讨论】:

  • 哪个 MySQL 版本?
  • 那你就不能使用窗口函数了。

标签: mysql sql inner-join greatest-n-per-group mysql-5.6


【解决方案1】:

你可以使用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
)

【讨论】:

  • @BaijNR:第二个查询适用于所有 MySQL 版本,如答案中所述。
【解决方案2】:
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

【讨论】:

    【解决方案3】:

    这是使用窗口函数的好地方:

    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 是一个 dbfiddle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多