经典SQL题库
1、查找员工编号emp_now为10001其自入职以来的薪水salary涨幅值growth
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`));
解题思路:巧妙使用max和min。
select (max(salary)-min(salary)) as groeth from salaries
where emp_no='10001'
2、
查找所有员工自入职以来的薪水涨幅情况,给出员工编号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`));
解题思路:
先用内连接构造两张当前薪水和入职薪水表,然后再内连接这两张表,筛选出emp_no和growth
select currentSalary.emp_no,(currentSalary.salary-beginSalary.salary) as growth
from (select e.emp_no,s.salary
from employees as e inner join salaries as s
on e.emp_no=s.emp_no where s.to_date=
'9999-01-01'
) as currentSalary
inner join(select e.emp_no,s.salary
from employees as e inner join salaries as s
on e.emp_no=s.emp_no where s.from_date=e.hire_date) as beginSalary
on currentSalary.emp_no=beginSalary.emp_no
order by growth