Skip to main content

LeetCode 1077. Project Employees III SQL Solution

Problem

LeetCode SQL Problem

  1. Project Employees III

Project table

project_idemployee_id
11
12
13
21
24

Employee table

employee_idnameexperience_years
1Khaled3
2Ali2
3John3
4Doe2

Solution - Rank() Window Function

Most experienced employees in each project
-- Use Rank() function to rank most experience employees in each project as 1
WITH ProjEmpExperienceRanked
AS (
SELECT P.project_id
,E.employee_id
,rank() OVER (
PARTITION BY P.project_id ORDER BY E.experience_years DESC
) AS rank_num
FROM Project AS P
INNER JOIN Employee AS E ON P.employee_id = E.employee_id
)
-- Report all employees with the maximum number of experience years in each project in case a tie
SELECT project_id
,employee_id
FROM ProjEmpExperienceRanked
WHERE rank_num = 1

Query Output

project_idemployee_id
11
13
21

Solution - CTE + Group By

Most experienced employees in each project
-- Use Group By to find out maximum experience years in each project
WITH ProjEmpMaxExperienceYear
AS (
SELECT P.project_id
,max(E.experience_years) AS max_experience_years
FROM Project AS P
INNER JOIN Employee AS E ON P.employee_id = E.employee_id
GROUP BY P.project_id
)
-- Report all employees with the maximum number of experience years in each project in case a tie
SELECT P.project_id
,P.employee_id
FROM Project AS P
INNER JOIN Employee AS E ON P.employee_id = E.employee_id
INNER JOIN ProjEmpMaxExperienceYear AS ME ON P.project_id = ME.project_id
AND E.experience_years = ME.max_experience_years

Query Output

project_idemployee_id
11
13
21