1、题目描述:
查找所有员工自入职以来的薪水涨幅情况,给出员工编号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`));
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`));
输入描述:
无
输出描述:
emp_no | growth |
---|---|
10011 | 0 |
省略 | 省略 |
10010 | 54496 |
10004 | 34003 |
2、代码:
充分利用中间临时表,先查出一个表,表里面存着 工号+入职时薪水,再查另一个表,表里存着 工号+现在的薪水,然后再对着两个临时表进行查询。
select ns.emp_no,(ns.salary-hs.salary) as growth from (select e.emp_no,s.salary from employees e left join salaries s on e.emp_no=s.emp_no where s.to_date='9999-01-01') as ns join (select e.emp_no,s.salary from employees e left join salaries s on e.emp_no=s.emp_no where s.from_date=e.hire_date) as hs on ns.emp_no=hs.emp_no order by growth;