【问题标题】:Find the salary of the youngest and eldest employee in each department查找每个部门中最年轻和最年长员工的工资
【发布时间】:2020-05-07 17:47:59
【问题描述】:

有两个表

1) Employee
id | Name |  Department | Dob 

2) Salary
id | salary

我想找到每个部门中最年轻和最年长的员工的薪水。 但是使用以下查询我无法获得正确的 id,salary。

SELECT salary.id,employee.Dept,salary.salary,MIN(employee.DoB) 
from employee 
INNER JOIN salary ON salary.id = employee.id  GROUP by Dept

上述查询返回正确的 Dob,但 ids 和薪水与出生日期不匹配。

【问题讨论】:

  • 您通常 GROUP BY 与您选择的列相同,但那些作为设置函数的参数的列除外。
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出您可以给出的最少代码,即您显示的代码可以通过您显示的代码扩展为不正常。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 停止尝试编写您的总体目标并从给定的代码中解释您的期望以及原因。

标签: mysql sql group-by inner-join having


【解决方案1】:

如果您运行的是 MySQL 8.0,只需使用窗口函数:

select *
from (
    select 
        e.*, 
        s.salary,
        row_number() over(partition by department order by dob asc) rn_asc,
        row_number() over(partition by department order by dob desc) rn_desc
    from employee e
    inner join salary s on s.id = employee.id
) t
where 1 in (rn_asc, rn_desc)

在早期版本中,一种选择是加入聚合查询:

select e.*, s.salary
from employee e
inner join salary s on s.id = employee.id
inner join (
    select department, min(dob) min_dob, max(dob) max_dob 
    from employee
    group by department
) d on d.department = e.department and e.dob in (d.min_dob, d.max_dob)

【讨论】:

  • 感谢您的回复这两个查询都对我有用
【解决方案2】:

我想我会在相关子查询中使用两次=

select s.*, e.department
from salary join
     employee e
     on s.id = e.id
where e.dob = (select min(e2.dob) from employee e where e2.department = e.department) or
      e.dob = (select max(e2.dob) from employee e where e2.department = e.department) ;

employee(department, dob) 上有一个索引,我希望它有很好的性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2013-05-23
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2016-06-20
    相关资源
    最近更新 更多