查找所有员工自入职以来的薪水涨幅情况

题目描述

查找所有员工自入职以来的薪水涨幅情况,给出员工编号emp_noy以及其对应的薪水涨幅growth,并按照growth进行升序

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`));

解题方案

本题的思路就在于分而治之,将入职薪资表和当前薪资表分别求得再进行关联,而入职工资就是employees表中的hire_date对应的日期再与salaries表关联可以得到;当前薪资可以通过日期为’9999-01-01’当做条件即可。

select s1.emp_no,(salary - old_salary) as growth
from (
        select emp_no ,salary 
        from salaries
        where to_date='9999-01-01'
    ) as s1 
    inner join (
    select e.emp_no , salary as old_salary
    from employees as e
            left join 
         salaries as s
            on e.emp_no = s.emp_no
               and e.hire_date = s.from_date
      )as f 
    on s1.emp_no = f.emp_no
order by growth

你可能感兴趣的:(SQL)