Skip to main content

Ranking Salary Deviations

HardPremium

Workday, a workforce management platform, wants to measure employee compensation intricacies. Every employee is anchored within a department, and the company want to identify those who exhibit the most significant deviations from the departmental norm.

You are given a table employees:

employee_idemployee_namedepartment_idsalary
1AliceA61000
2BobB75000
3CarolA59000
4DavidC57000
5EmilyB70000
6FrankC58000
7GraceA62000
8HenryB77000
9IvyC59000
10JackA64000

Craft a SQL query that orchestrates the ranking of employees based on their divergence from the department's average salary. You should provide the employee's name, their department, individual salary, the department's average salary, and an assigned rank. This ranking corresponds to the magnitude of difference between the employee's salary and the department's average (rank 1 = most noteworthy deviation).

If two employees from the same department have salaries that deviate to the same extent, let them share the same rank.

Desired output:

employee_namedepartment_idsalaryavg_salarydeviation_rank
"Carol""A"59000615001
"Jack""A"64000615001
"Alice""A"61000615002
"Grace""A"62000615002
"Emily""B"70000740001
"Henry""B"77000740002
"Bob""B"75000740003
"David""C"57000580001
"Ivy""C"59000580001
"Frank""C"58000580002