需要分别找到入职时的薪水和当前薪水。入职时的薪水,可以通过employees表中的hire_date和salaries中的from_date来确定,当前薪水通过to_date='9999-01-01'来确定,再连接两个表,相减可得出薪水涨幅,最后使用order by排序
代码块 SELECT e.emp_no,(s2.salary-s1.salary) AS growth FROM salaries AS s1 JOIN employees AS e ON e.emp_no=s1.emp_no JOIN ( SELECT emp_no,salary FROM salaries WHERE to_date='9999-01-01' ) AS s2 ON e.emp_no=s2.emp_no WHERE e.hire_date=s1.from_date ORDER BY growth
上述代码还可以继续简化:
直接联结两次salaries表,第一次以入职时间作为筛选条件(e.hire_date=s1.from_date),第二次以现在的时间作为筛选条件(s2.to_date='9999-01-01')
SELECT e.emp_no,(s2.salary-s1.salary) AS growth FROM employees AS e LEFT JOIN salaries AS s1 ON e.emp_no=s1.emp_no LEFT JOIN salaries AS s2 ON e.emp_no=s2.emp_no WHERE e.hire_date=s1.from_date AND s2.to_date='9999-01-01' ORDER BY growth