自连接查询——获取当前薪水第二多的员工编号
题目描述
有一个员工表employees简况如下:
有一个薪水表salaries简况如下:
请你查找薪水排名第二多的员工编号emp_no、薪水salary、last_name以及first_name,不能使用order by完成,以上例子输出为:
自连接后:
s1.salary | s2.salary |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 1 |
2 | 2 |
2 | 3 |
3 | 1 |
3 | 2 |
3 | 3 |
限定s1.salary<=s2.salary后
s1.salary | s2.salary |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 2 |
2 | 3 |
3 | 3 |
group by s1.salary 后
s1.salary | count(distinct s2.salary) |
---|---|
1 | 3 |
2 | 2 |
3 | 1 |
如果找第n名,那么count(distinct s2.salary)即等于n
-- 方法二:自连接查询
select s.emp_no, s.salary, e.last_name, e.first_name
from salaries s join employees e
on s.emp_no = e.emp_no
where s.salary =
(
select s1.salary
from salaries s1 join salaries s2 -- 自连接查询
on s1.salary <= s2.salary
group by s1.salary -- 当s1<=s2链接并以s1.salary分组时一个s1会对应多个s2
having count(distinct s2.salary) = 2 -- (去重之后的数量就是对应的名次)
)