获取当前薪水第二多的员工的emp_no以及其对应的薪水salary

sql实战 获取当前薪水第二多的员工的emp_no以及其对应的薪水salary

  • 问题描述
  • Sql语句

问题描述

查找当前薪水(to_date=‘9999-01-01’)排名第二多的员工编号emp_no、薪水salary、last_name以及first_name,你可以不使用order by完成吗
CREATE TABLE employees (
emp_no int(11) NOT NULL,
birth_date date NOT NULL,
first_name varchar(14) NOT NULL,
last_name varchar(16) NOT NULL,
gender char(1) NOT NULL,
hire_date date NOT NULL,
PRIMARY KEY (emp_no));
CREATE TABLE salaries (
emp_no int(11) NOT NULL,
salary int(11) NOT NULL,
from_date date NOT NULL,
to_date date NOT NULL,
PRIMARY KEY (emp_no,from_date));

来源:牛客网
链接:https://www.nowcoder.com/practice/c1472daba75d4635b7f8540b837cc719?tpId=82&tqId=29770&tPage=1&rp=&ru=/ta/sql&qru=/ta/sql/question-ranking

Sql语句

思路:1、先找到当前最大薪水,再找到当前比最大薪水晓得所有薪水,再找第二大薪水,再根据第二大薪水找信息
          2、先让薪水表自关联,再找出第二个表的薪水比第一个表的薪水大于等于的,并且关联出来第二个表的薪水数量为2的薪水,再根据薪水找信息

select a.emp_no, b.salary, a.last_name, a.first_name
from employees as a left join salaries as b on a.emp_no = b.emp_no
where salary = (
    select max(salary)
    from salaries
    where to_date='9999-01-01'
    and salary < (
        select max(salary)
        from salaries
        where to_date='9999-01-01'
            )
    )
select s.emp_no, s.salary, e.last_name, e.first_name
from salaries as s join employees as e on s.emp_no = e.emp_no
where s.salary =
    (
    select s1.salary
    from salaries s1 join salaries s2 on s1.salary <= s2.salary
    group by s1.salary
    having count(distinct s2.salary) = 2
    and s1.to_date = '9999-01-01'
    )
and s.to_date = '9999-01-01'

你可能感兴趣的:(SQL实战)