WITH employee_performance AS (
SELECT e.employee_id,
e.employee_name,
e.department,
p.rating AS latest_rating,
LAG(p.rating) OVER (PARTITION BY e.employee_id ORDER BY p.review_date) AS previous_rating,
ROW_NUMBER() OVER (PARTITION BY e.employee_id ORDER BY p.review_date DESC) AS rn,
RANK() OVER (PARTITION BY e.department ORDER BY p.rating DESC) AS dept_rank,
ROUND(AVG(p.rating) OVER (PARTITION BY e.department), 2) AS dept_avg_rating
FROM employees e
JOIN performance p ON e.employee_id = p.employee_id
)
SELECT employee_id,
employee_name,
department,
latest_rating,
COALESCE(previous_rating, 0) AS previous_rating,
ROUND(latest_rating - COALESCE(previous_rating, 0), 2) AS improvement,
dept_rank,
dept_avg_rating,
CASE WHEN latest_rating > dept_avg_rating THEN 'Above Average'
WHEN latest_rating = dept_avg_rating THEN 'At Average'
ELSE 'Below Average'
END AS performance_vs_dept
FROM employee_performance
WHERE rn = 1
ORDER BY department, dept_rank;
💡 Explanation
- This step combines multiple window functions to provide a comprehensive performance analysis for each employee.
- RANK() OVER (PARTITION BY e.department ORDER BY p.rating DESC) ranks employees within their department based on their latest rating. Employees with the same rating get the same rank, and the next rank skips accordingly.
- AVG(p.rating) OVER (PARTITION BY e.department) calculates the average rating for each department. This window function operates on all rows within each department partition.
- The window frame includes all rows in the partition by default, so this calculates the average of all performance ratings in that department.
- LAG() is used again to get the previous rating for improvement tracking.
- The CASE statement compares each employee's latest rating against their department's average to classify them as 'Above Average', 'At Average', or 'Below Average'.
- WHERE rn = 1 ensures we're working with the latest performance record for each employee.
- ORDER BY department, dept_rank organizes the output by department and then by ranking within that department.