题解 | #获取每个部门中当前员工薪水最高的相关信息#
获取每个部门中当前员工薪水最高的相关信息
http://www.nowcoder.com/practice/4a052e3e1df5435880d4353eb18a91c6
Mysql与Sqlite select 非聚合列的结果是 不一样的,假使本题只要求输出:
dept_no,maxSalary两列,则只需使用max聚合函数:
select de.dept_no,max(sa.salary) as maxSalary
from dept_emp as de left join salaries as sa
on de.emp_no=sa.emp_no
group by de.dept_no
order by de.dept_no asc
但本体需要select emp_no这个非聚合字段,而一个聚合字段(dept_no)对应多个非聚合字段(emp_no),所以选择的时候,Sqlite会随机选择非聚合字段中的任何一个(而非选择max(sa.salary)最大工资对应的那一个emp_no),而mysql会直接报错! 这是select 非聚合字段,经典问题!!!
解决方法: 先构造一个子表t1(聚合同部门工资值),用于查找最大工资max(sa.salary) 与其dept_no,
(
select de.dept_no,max(sa.salary) as salary
from dept_emp as de left join salaries as sa
on de.emp_no=sa.emp_no
group by dept_no
) as t1
再构建一个子表t2(不聚和表中同部门的工资值,只合并两表),存储dept_no,salary(t2中的dept_no,salary用来和t1中的dept_no,salary比对),emp_no
(
select de.dept_no,de.emp_no,sa.salary
from dept_emp as de left join salaries as sa
on de.emp_no=sa.emp_no
) as t2
t1,t2两子表联合查询:
select t2.dept_no,t2.emp_no,t1.salary as maxSalary from
(
select de.dept_no,max(sa.salary) as salary
from dept_emp as de left join salaries as sa
on de.emp_no=sa.emp_no
group by dept_no
) as t1 left join
(
select de.dept_no,de.emp_no,sa.salary
from dept_emp as de left join salaries as sa
on de.emp_no=sa.emp_no
) as t2
on t1.dept_no=t2.dept_no and t1.salary=t2.salary
order by t2.dept_no asc