时间限制:1秒 空间限制:32768K 热度指数:47763
题目描述
查找所有员工自入职以来的薪水涨幅情况,给出员工编号emp_no以及其对应的薪水涨幅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`));
写法一:
先分别用两次INNER JOIN内连接employees与salaries,建立两张表,分别存放员工当前工资(current_salary)与员工入职时的工资(hier_salary),再用INNER JOIN连接current_salary与hier_salary,最后限定在同一员工下用当前工资减去入职工资。
select current_salary.emp_no,(current_salary.salary-hire_salary.salary) growth
from (select e.emp_no,s.salary from employees e
inner join salaries s on s.emp_no=e.emp_no where s.to_date='9999-01-01')
as current_salary
inner join (select e.emp_no,s.salary from employees e
inner join salaries s on s.emp_no=e.emp_no where s.from_date=e.hire_date)
as hire_salary
on current_salary.emp_no=hire_salary.emp_no
order by growth asc
写法二:
select e.emp_no,(b.salary-c.salary) growth
from employees as e inner join salaries b
on b.emp_no=e.emp_no and b.to_date='9999-01-01'
inner join salaries c on c.emp_no=e.emp_no and c.from_date=e.hire_date
order by growth asc