Resolved: Confusing 4 full-years definition - Ranking window function & Join solution
Hi, from my understanding of the exercise, the requirement is to check for 4 full years between the hire_date and the from_date.
However, the clause AND YEAR(s.from_date) - YEAR(e.hire_date) >= 5
might produce misleading results.
Example:
Take employee 10501
, hired on 1987-04-20
. Four full years after the hire date would be 1991-04-20
. We should only include rows where the from_date is later than 1991-04-20
.
Now, there is a row with from_date = 1991-09-08
, which is clearly more than 4 full years after the hire_date
. However, it would be excluded because the YEAR() difference (5 years) is calculated without considering the exact month and day, leading to incorrect results.
Here's my code:
SELECT
e.emp_no,
DENSE_RANK() OVER w as employee_salary_ranking,
s.salary,
e.hire_date,
s.from_date,
DATE_ADD(e.hire_date, INTERVAL 4 YEAR)
FROM employees e
JOIN salaries s ON s.emp_no = e.emp_no
AND s.from_date > DATE_ADD(e.hire_date, INTERVAL 4 YEAR)
WHERE e.emp_no BETWEEN 10500 AND 10600
WINDOW w as (PARTITION BY e.emp_no ORDER BY s.salary DESC)
;
Please correct me if I misunderstood the question.
Thank you
Thanks for reaching out.
Your understanding of the requirement is correct! The
YEAR()
difference ignores months and days, which might lead to errors. Using DATE_ADD(e.hire_date, INTERVAL 4 YEAR)
ensures the exact date comparison. This resolves the issue you mentioned. Great work!Hope this helps.
Best,
Tsvetelin