现有两张表,一张员工信息表(employees)和一张工资表(salaries),需要编写一个查询语句,查找出所有员工自入职以来的薪资涨幅情况,输出员工编号emp_id、员工姓名name和对应的薪水涨幅growth。
员工信息表中包含的字段如下:
emp_id int not null
name varchar(20) not null
hire_date date not null
工资表中包含的字段如下:
emp_id int not null,
salary int not null,
from_date date not null,
to_date date not null
示例数据如下:
员工信息表:
工资表:
方法一:使用链接查询
第一步,查找出每个员工入职时的工资,即工资表中的开始计薪日期等于员工信息表中的雇佣日期。
select e.emp_id,e.name,s.salary
from employees e
inner join
salaries s
on e.emp_id=s.emp_id
and e.hire_date=s.from_date;
第二步,查找出每个员工当前的工资,假设当前日期为‘2020-04-03’。
select emp_id,salary
from salaries
where to_date='2020-04-03';
第三步,连接两个临时表,用当前工资减去入职工资得到每个员工的薪水涨幅growth。
select t1.emp_id,t1.name,t2.salary-t1.salary as growth
from(
select e.emp_id,e.name,s.salary
from employees e
inner join
salaries s
on e.emp_id=s.emp_id
and e.hire_date=s.from_date
)t1
inner join
(
select emp_id,salary
from salaries
where to_date='2020-04-03'
)t2
on t1.emp_id=t2.emp_id
order by growth desc;
方法二:使用from并列查询
select e.emp_id,e.name,s2.salary-s1.salary as growth
from employees e,salaries s1,salaries s2
where e.emp_id=s1.emp_id
and s1.emp_id=s2.emp_id
and e.hire_date=s1.from_date
and s2.to_date='2020-04-03'
order by growth desc;