|
| 1 | +-- Question 85 |
| 2 | +-- Table: Project |
| 3 | + |
| 4 | +-- +-------------+---------+ |
| 5 | +-- | Column Name | Type | |
| 6 | +-- +-------------+---------+ |
| 7 | +-- | project_id | int | |
| 8 | +-- | employee_id | int | |
| 9 | +-- +-------------+---------+ |
| 10 | +-- (project_id, employee_id) is the primary key of this table. |
| 11 | +-- employee_id is a foreign key to Employee table. |
| 12 | +-- Table: Employee |
| 13 | + |
| 14 | +-- +------------------+---------+ |
| 15 | +-- | Column Name | Type | |
| 16 | +-- +------------------+---------+ |
| 17 | +-- | employee_id | int | |
| 18 | +-- | name | varchar | |
| 19 | +-- | experience_years | int | |
| 20 | +-- +------------------+---------+ |
| 21 | +-- employee_id is the primary key of this table. |
| 22 | + |
| 23 | + |
| 24 | +-- Write an SQL query that reports the most experienced employees in each project. |
| 25 | +-- In case of a tie, report all employees with the maximum number of experience years. |
| 26 | + |
| 27 | +-- The query result format is in the following example: |
| 28 | + |
| 29 | +-- Project table: |
| 30 | +-- +-------------+-------------+ |
| 31 | +-- | project_id | employee_id | |
| 32 | +-- +-------------+-------------+ |
| 33 | +-- | 1 | 1 | |
| 34 | +-- | 1 | 2 | |
| 35 | +-- | 1 | 3 | |
| 36 | +-- | 2 | 1 | |
| 37 | +-- | 2 | 4 | |
| 38 | +-- +-------------+-------------+ |
| 39 | + |
| 40 | +-- Employee table: |
| 41 | +-- +-------------+--------+------------------+ |
| 42 | +-- | employee_id | name | experience_years | |
| 43 | +-- +-------------+--------+------------------+ |
| 44 | +-- | 1 | Khaled | 3 | |
| 45 | +-- | 2 | Ali | 2 | |
| 46 | +-- | 3 | John | 3 | |
| 47 | +-- | 4 | Doe | 2 | |
| 48 | +-- +-------------+--------+------------------+ |
| 49 | + |
| 50 | +-- Result table: |
| 51 | +-- +-------------+---------------+ |
| 52 | +-- | project_id | employee_id | |
| 53 | +-- +-------------+---------------+ |
| 54 | +-- | 1 | 1 | |
| 55 | +-- | 1 | 3 | |
| 56 | +-- | 2 | 1 | |
| 57 | +-- +-------------+---------------+ |
| 58 | +-- Both employees with id 1 and 3 have the |
| 59 | +-- most experience among the employees of the first project. For the second project, the employee with id 1 has the most experience. |
| 60 | + |
| 61 | +-- Solution |
| 62 | +with t1 as( |
| 63 | +select p.project_id, p.employee_id, e.experience_years, |
| 64 | +rank() over(partition by project_id order by experience_years desc) as rk |
| 65 | +from project p |
| 66 | +join employee e |
| 67 | +on p.employee_id = e.employee_id) |
| 68 | + |
| 69 | +select t1.project_id, t1.employee_id |
| 70 | +from t1 |
| 71 | +where t1.rk = 1 |
0 commit comments