1077. Project Employees III 难度:中等

1、题目描述

Write an SQL query that reports the most experienced employees in each project. In case of a tie, report all employees with the maximum number of experience years.
The query result format is in the following example:
Project table:

project_id employee_id
1 1
1 2
1 3
2 1
2 4

Employee table:

employee_id name experience_years
1 Khaled 3
2 Ali 2
3 John 3
4 Doe 2

Result table:

project_id employee_id
1 1
1 3
2 1

Both employees with id 1 and 3 have the most experience among the employees of the first project. For the second project, the employee with id 1 has the most experience.

来源:力扣(LeetCode)

2、解题思路

主要是出现多个最多经验的,重复数据处理
1# 首选2表联查,找出每个project_id最大经验值

select project_id,e.employee_id,max(experience_years) as `years`
from Project p left join Employee e 
on e.employee_id=p.employee_id
group by project_id

2# 然后,Project、Employee还有表,3表联查,条件是experience_years等于上述最大经验值

3、提交记录

select p0.project_id,p0.employee_id

from Project p0 left join Employee e0
on p0.employee_id=e0.employee_id 

left join

(select project_id,e.employee_id,max(experience_years) as `years`
from Project p left join Employee e 
on e.employee_id=p.employee_id
group by project_id) max1

on p0.project_id=max1.project_id
where e0.experience_years=max1.`years`

1190ms

发布了90 篇原创文章 · 获赞 3 · 访问量 4935

猜你喜欢

转载自blog.csdn.net/weixin_43329319/article/details/97615687