题解 | #获取每个部门中当前员工薪水最高的相关信息#
获取每个部门中当前员工薪水最高的相关信息
http://www.nowcoder.com/practice/4a052e3e1df5435880d4353eb18a91c6
- 错误思路:找到每个部门最高的salary,再用该salary直接匹配对应的人
- 易错点:没有考虑直接用salary连接,有可能出现不同部门的人有相同salary的情况,因此必须要增加一个限制同部门的条件(重新连一个有部门号、员工号和工资的宽表)
- 以下是错误代码示范
select a.dept_no, ss.emp_no, a.salary as maxSalary
from
(
# 每个部门最高工资
select dep.dept_no, max(s.salary)as salary
from salaries as s
left join
(
select emp_no, dept_no
from dept_emp
)as dep on dep.emp_no = s.emp_no
group by 1
)as a
left join # 用salary直接找对应的人,错误!
(
select emp_no, salary
from salaries
)as ss on ss.salary = a.salary
order by 1
以下是正确代码:
select a.dept_no, b.emp_no, a.salary as maxSalary
from
(
# 每个部门最高工资
select dep.dept_no, max(s.salary)as salary
from salaries as s
left join
(
select emp_no, dept_no
from dept_emp
)as dep on dep.emp_no = s.emp_no
group by 1
)as a
left join
(
# 部门、员工、工资的宽表
select s.emp_no, dep.dept_no, s.salary
from salaries as s
left JOIN
(
select emp_no, dept_no
from dept_emp
)as dep on dep.emp_no = s.emp_no
)as b on b.salary = a.salary and b.dept_no = a.dept_no
order by 1