|
| 1 | +This SQL query uses the `ROW_NUMBER()` function to assign a unique row number to each employee within their respective department, sorted by their salary in descending order. This is done within a Common Table Expression (CTE) named Employee_CTE. |
| 2 | + |
| 3 | +In the main query, it selects the employees from Employee_CTE and joins them with the Departments table to get the department name. Finally, it filters to only get the top three highest-paid employees from each department. |
| 4 | + |
| 5 | +The result is a list of employees, with each row containing the employee’s ID, first name, last name, department ID, salary, department name, and their rank within their department based on salary. The employees are ordered by their department ID and their rank within the department. |
| 6 | + |
| 7 | +```sql |
| 8 | +WITH Employee_CTE AS ( |
| 9 | + SELECT |
| 10 | + EmployeeID, |
| 11 | + FirstName, |
| 12 | + LastName, |
| 13 | + DepartmentID, |
| 14 | + Salary, |
| 15 | + ROW_NUMBER() OVER ( |
| 16 | + PARTITION BY DepartmentID |
| 17 | + ORDER BY Salary DESC |
| 18 | + ) AS RowNumber |
| 19 | + FROM |
| 20 | + Employees |
| 21 | +) |
| 22 | +SELECT |
| 23 | + E1.EmployeeID, |
| 24 | + E1.FirstName, |
| 25 | + E1.LastName, |
| 26 | + E1.DepartmentID, |
| 27 | + E1.Salary, |
| 28 | + D.DepartmentName, |
| 29 | + E1.RowNumber |
| 30 | +FROM |
| 31 | + Employee_CTE E1 |
| 32 | +JOIN |
| 33 | + Departments D ON E1.DepartmentID = D.DepartmentID |
| 34 | +WHERE |
| 35 | + E1.RowNumber <= 3 |
| 36 | +ORDER BY |
| 37 | + E1.DepartmentID, |
| 38 | + E1.RowNumber; |
| 39 | + |
| 40 | +``` |
0 commit comments