|
| 1 | +/* |
| 2 | +Question 3580. Find Consistently Improving Employees |
| 3 | +Link: https://leetcode.com/problems/find-consistently-improving-employees/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: employees |
| 6 | +
|
| 7 | ++-------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++-------------+---------+ |
| 10 | +| employee_id | int | |
| 11 | +| name | varchar | |
| 12 | ++-------------+---------+ |
| 13 | +employee_id is the unique identifier for this table. |
| 14 | +Each row contains information about an employee. |
| 15 | +Table: performance_reviews |
| 16 | +
|
| 17 | ++-------------+------+ |
| 18 | +| Column Name | Type | |
| 19 | ++-------------+------+ |
| 20 | +| review_id | int | |
| 21 | +| employee_id | int | |
| 22 | +| review_date | date | |
| 23 | +| rating | int | |
| 24 | ++-------------+------+ |
| 25 | +review_id is the unique identifier for this table. |
| 26 | +Each row represents a performance review for an employee. The rating is on a scale of 1-5 where 5 is excellent and 1 is poor. |
| 27 | +Write a solution to find employees who have consistently improved their performance over their last three reviews. |
| 28 | +
|
| 29 | +An employee must have at least 3 review to be considered |
| 30 | +The employee's last 3 reviews must show strictly increasing ratings (each review better than the previous) |
| 31 | +Use the most recent 3 reviews based on review_date for each employee |
| 32 | +Calculate the improvement score as the difference between the latest rating and the earliest rating among the last 3 reviews |
| 33 | +Return the result table ordered by improvement score in descending order, then by name in ascending order. |
| 34 | +*/ |
| 35 | + |
| 36 | +WITH review_dates AS ( |
| 37 | + SELECT |
| 38 | + employee_id, |
| 39 | + MAX(review_date) AS review_date |
| 40 | + FROM performance_reviews |
| 41 | + GROUP BY employee_id |
| 42 | +), |
| 43 | + |
| 44 | +review_ratings AS ( |
| 45 | + SELECT |
| 46 | + pr.employee_id, |
| 47 | + pr.review_date, |
| 48 | + pr.rating, |
| 49 | + LAG(pr.rating, 1, NULL) OVER (PARTITION BY pr.employee_id ORDER BY pr.review_date) AS second_rating, |
| 50 | + LAG(pr.rating, 2, NULL) OVER (PARTITION BY pr.employee_id ORDER BY pr.review_date) AS third_rating |
| 51 | + FROM performance_reviews AS pr |
| 52 | +) |
| 53 | + |
| 54 | +SELECT |
| 55 | + e.employee_id, |
| 56 | + e.name, |
| 57 | + rr.rating - rr.third_rating AS improvement_score |
| 58 | +FROM employees AS e |
| 59 | +LEFT JOIN |
| 60 | + review_dates AS rd |
| 61 | + ON e.employee_id = rd.employee_id |
| 62 | +INNER JOIN |
| 63 | + review_ratings AS rr |
| 64 | + ON |
| 65 | + e.employee_id = rr.employee_id |
| 66 | + AND rd.review_date = rr.review_date |
| 67 | +WHERE rr.rating > rr.second_rating AND rr.second_rating > rr.third_rating |
| 68 | +ORDER BY improvement_score DESC, e.name ASC |
0 commit comments