To solve this problem, we need to retrieve the top-earning employee from each department, ordered by department name. The solution involves using a window function to rank employees within each department by their salary and then selecting the highest earner from each group.
Approach
Join Tables: Combine the
employees
anddepartments
tables to get the department names associated with each employee.Rank Employees: Use the
ROW_NUMBER()
window function to rank employees within each department based on their salary in descending order. To handle ties (employees with the same salary), we break the tie by sorting onemployee_id
in ascending order.Filter Top Earners: Select only the employees ranked first in their respective departments.
Order Results: Sort the final result by department name alphabetically.
Solution Code
WITH ranked_employees AS ( SELECT d.name AS department_name, e.id AS employee_id, e.first_name, e.last_name, e.salary, ROW_NUMBER() OVER ( PARTITION BY e.department_id ORDER BY e.salary DESC, e.id ASC ) AS rn FROM employees e JOIN departments d ON e.department_id = d.id ) SELECT department_name, employee_id, first_name, last_name, salary FROM ranked_employees WHERE rn = 1 ORDER BY department_name;
Explanation
Common Table Expression (CTE): The
ranked_employees
CTE joins theemployees
anddepartments
tables to combine employee details with their department names. TheROW_NUMBER()
function assigns a unique rank to each employee within their department. Employees are ordered by:salary DESC
to prioritize higher salaries.employee_id ASC
to break ties, ensuring consistent results by selecting the employee with the smallest ID first.
Main Query: Filters the results from the CTE to include only the top-ranked employees (
rn = 1
) from each department.Ordering: The final result is ordered by
department_name
to meet the specified output requirement.
No comments:
Post a Comment