#数据库SQL实战#【Day5】
--------------------------------------------------
学习用,欢迎讨论。
--------------------------------------------------
查看详细题目的方法:
复制以下题目内容;
Ctrl+F查找刚刚复制的题目即可。
--------------------------------------------------
题目17:获取当前薪水第二多的员工的emp_no以及其对应的薪水salary
select emp_no, salary from salaries where to_date = '9999-01-01' order by salary desc limit 1, 1
上面是最直接的想法,但是没有考虑到员工工资相同的情况。进而有如下想法:
select emp_no, salary from salaries where to_date = '9999-01-01' and salary = ( select salary from salaries where to_date = '9999-01-01' group by salary order by salary desc limit 1, 1 )
通过子查询选出排在第二的工资,然后查找是这一工资的员工。
--------------------------------------------------
题目18:查找当前薪水排名第二多的员工编号emp_no
本题和题目17类似,但是题目要求不能使用order by,思路如下:
select e.emp_no, max(s.salary), e.last_name, e.first_name from employees as e inner join salaries as s on e.emp_no = s.emp_no where s.to_date = '9999-01-01' and s.salary < (select max(salary) from salaries where to_date = '9999-01-01')
同样,这样的思路没有考虑到员工工资相同的情况,和题目17类似,也有如下思路:
select e.emp_no, s.salary, e.last_name, e.first_name from employees as e inner join salaries as s on e.emp_no = s.emp_no where s.to_date = '9999-01-01' and s.salary = ( select max(salary) from salaries where to_date = '9999-01-01' and salary < ( select max(salary) from salaries where to_date = '9999-01-01' ) )
--------------------------------------------------
题目19:查找所有员工的last_name和first_name以及对应的dept_name
select e.last_name, e.first_name, d.dept_name from employees as e left join dept_emp as de on e.emp_no = de.emp_no left join departments as d on de.dept_no = d.dept_no
直接两次使用left join即可得到结果。
--------------------------------------------------
题目20:查找员工编号emp_no为10001其自入职以来的薪水salary涨幅值growth
本题的关键在于对“自入职以来的薪水salary涨幅值”的定义,定义不同可以有不同的结果。
其一,涨幅值就是现在的薪水减去刚刚入职时候的薪水
select ( (select salary from salaries where emp_no = 10001 order by from_date desc limit 1)- (select salary from salaries where emp_no = 10001 order by from_date limit 1) ) as growth
其二,涨幅值就是最大薪水减去最小薪水
select max(salary) - min(salary) as growth from salaries where emp_no = 10001
以上都能通过测试,是因为数据比较特殊。当然,对于涨幅值也能有其他的理解。
--------------------------------------------------