题目:
有一个员工表employees简况如下:
emp_no | birth_date | first_name | last_name | gender | hire_date |
10001 | 1953-09-02 | Georgi | Facello | M | 2001-06-22 |
10002 | 1964-06-02 | Bezalel | Simmel | F | 1999-08-03 |
有一个薪水表salaries简况如下:
emp_no | salary | from_date | to_date |
10001 | 85097 | 2001-06-22 | 2002-06-22 |
10001 | 88958 | 2002-06-22 | 9999-01-01 |
10002 | 72527 | 1999-08-03 | 2000-08-02 |
10002 | 72527 | 2000-08-02 | 2001-08-02 |
请你查找在职员工自入职以来的薪水涨幅情况,给出在职员工编号emp_no以及其对应的薪水涨幅growth,并按照growth进行升序,以上例子输出为
(注: to_date为薪资调整某个结束日期,或者为离职日期,to_date='9999-01-01'时,表示依然在职,无后续调整记录)
emp_no | growth |
10001 | 3861 |
题解:
我的做法:找出薪水表最大to_data是9999-01-01的emp_no,再找到各自最低、最高薪水,求差值
错的原因:在职期间有可能降薪,也就是最低薪水有可能不在入职当天,题目求的是入职以来的,差值应该是to_data是9999-01-01的薪水减去hire_date时的薪水
正确做法:员工表和两张薪水表join,相同emp_no的hire_date与from_date一样以及to_date是9999-01-01
select
e.emp_no,
s2.salary - s1.salary as `growth`
from
employees e
inner join
salaries s1
on
e.emp_no = s1.emp_no
and e.hire_date = s1.from_date
inner join
salaries s2
on
e.emp_no = s2.emp_no
and s2.to_date = '9999-01-01'
order by
`growth` asc