题解 | 查找在职员工自入职以来的薪水涨幅情况
查找在职员工自入职以来的薪水涨幅情况
https://www.nowcoder.com/practice/fc7344ece7294b9e98401826b94c6ea5
select
initial.emp_no,
(current_salary - initial_salary) as growth
from
(select
e.emp_no,
salary as initial_salary
from
employees e
left join
salaries s
on e.emp_no = s.emp_no
where
from_date = hire_date) as initial
join
(select
e.emp_no,
salary as current_salary
from
employees e
left join
salaries s1
on e.emp_no = s1.emp_no
where to_date = '9999-01-01') as current
on initial.emp_no = current.emp_no
order by
growth
- 总体思路这段 SQL 代码的目的是计算在职员工(to_date为9999-01-01)自入职以来的薪水涨幅情况。它通过两个子查询分别找到员工的入职薪水和当前薪水,然后计算两者的差值得到薪水涨幅,并按照涨幅进行排序。
- 子查询 1:找到入职薪水第一个子查询的目的是找到每个员工的入职薪水。
收起
sql
(select
e.emp_no,
salary as initial_salary
from
employees e
left join
salaries s
on e.emp_no = s.emp_no
where
from_date = hire_date) as initial
- 这里使用了
LEFT JOIN将employees表和salaries表连接起来。连接条件是e.emp_no = s.emp_no,即员工编号相同。 - 筛选条件
from_date = hire_date确保找到的是员工入职时的薪水记录。 - 这个子查询返回两列:
emp_no(员工编号)和initial_salary(入职薪水),并将结果集命名为initial。
- 子查询 2:找到当前薪水第二个子查询的目的是找到每个在职员工的当前薪水。
收起
sql
(select
e.emp_no,
salary as current_salary
from
employees e
left join
salaries s1
on e.emp_no = s1.emp_no
where to_date = '9999-01-01') as current
- 同样使用了
LEFT JOIN将employees表和salaries表连接起来。 - 筛选条件
to_date = '9999-01-01'确保找到的是在职员工的当前薪水记录(通常9999-01-01表示员工仍然在职)。 - 这个子查询返回两列:
emp_no(员工编号)和current_salary(当前薪水),并将结果集命名为current。
- 计算薪水涨幅并排序主查询将两个子查询的结果集通过emp_no进行连接:
收起
sql
select
initial.emp_no,
(current_salary - initial_salary) as growth
from
(子查询1) as initial
join
(子查询2) as current
on initial.emp_no = current.emp_no
order by
growth
- 它计算了
current_salary和initial_salary的差值,得到薪水涨幅growth。 - 最后,按照
growth进行升序排序,这样就可以得到在职员工自入职以来的薪水涨幅情况,并按照涨幅从小到大排列。
总的来说,这段代码通过巧妙地使用子查询和连接操作,实现了计算在职员工薪水涨幅的功能。
基恩士成长空间 440人发布