题解 | #获取每个部门中当前员工薪水最高的相关信息#

获取每个部门中当前员工薪水最高的相关信息

http://www.nowcoder.com/practice/4a052e3e1df5435880d4353eb18a91c6

Step1: it is straightforward to use INNER JOIN to collect all required info from given tables. So we could create one table just containing the results columns using Inner JOIN

Step2. we know that once GROUP BY is used then all columns that appear in the SELECT clause only have 3 alternatives: columns that appear in GROUP BY; CONSTANT; AGG functions like MAX() in this case. SO if we want to get the final result with three columns. The first column dept_no is easy to get since it appears in GROUB BY, max salary is available as well since it appears in AGG function. But emp_no cannot be selected in the SELECT clause since it is not in any of the 3 alternatives. Then we could create another table where we use GROUP BY to get the highest salary per department.

step3: SELECT all expected columns in order from two tables. syntax is:

SELECT * FROM 
(SELECT * FROM ....) AS table1 # alias 
(SELECT * FROM ....) AS table2 # alias 
WHERE ... # condition
ORDER BY ...; 

Final codes:

SELECT table1.dept_no, table1.emp_no, table2.maxSalary FROM 

(SELECT dept_no, dept_emp.emp_no, salary FROM dept_emp 
INNER JOIN salaries 
ON dept_emp.emp_no=salaries.emp_no) AS table1,

(SELECT dept_emp.dept_no, MAX(salary) AS maxSalary FROM dept_emp
INNER JOIN salaries
ON dept_emp.emp_no=salaries.emp_no
GROUP BY dept_emp.dept_no) AS table2

WHERE table1.dept_no=table2.dept_no AND table1.salary=table2.maxSalary
ORDER BY table1.dept_no ASC;
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:48
点赞 评论 收藏
分享
ProMonkey2024:5个oc?厉害! 但是有一个小问题:谁问你了?😡我的意思是,谁在意?我告诉你,根本没人问你,在我们之中0人问了你,我把所有问你的人都请来 party 了,到场人数是0个人,誰问你了?WHO ASKED?谁问汝矣?誰があなたに聞きましたか?누가 물어봤어?我爬上了珠穆朗玛峰也没找到谁问你了,我刚刚潜入了世界上最大的射电望远镜也没开到那个问你的人的盒,在找到谁问你之前我连癌症的解药都发明了出来,我开了最大距离渲染也没找到谁问你了我活在这个被辐射蹂躏了多年的破碎世界的坟墓里目睹全球核战争把人类文明毁灭也没见到谁问你了(别的帖子偷来的,现学现卖😋)
点赞 评论 收藏
分享
评论
2
收藏
分享
牛客网
牛客企业服务