Query departments and top earners
MicrosoftData Scientist · Technical ScreenLast updated
This problem tests your ability to aggregate data using window functions to identify top-performing rows within specific groups and perform conditional filtering across joined tables.
Problem Statement
You are working with two tables: employees and departments.
Table Schema
employees
id: INT (Primary Key)name: VARCHARsalary: INTdepartment_id: INT
departments
id: INT (Primary Key)name: VARCHAR
Task
Write a SQL query to identify the top earners in each department. A "top earner" is defined as an employee whose salary is strictly in the top 3 within their department. If multiple employees share the same salary, they should still be included as long as their rank is <= 3.
Expected Output
Return a result set containing the Department Name, Employee Name, and Salary, ordered by Department Name (alphabetical) and Salary (descending).
Example
Input:
employees: (1, 'Alice', 90000, 1), (2, 'Bob', 80000, 1), (3, 'Charlie', 90000, 1), (4, 'David', 70000, 1), (5, 'Eve', 60000, 2)
departments: (1, 'Engineering'), (2, 'Sales')
Output:
| Department | Name | Salary |
|---|---|---|
| Engineering | Alice | 90000 |
| Engineering | Charlie | 90000 |
| Engineering | Bob | 80000 |
| Sales | Eve | 60000 |
Constraints
- Use
DENSE_RANK()orRANK()appropriately to handle ties. - Assume
department_idis a valid foreign key.
Hints
Hint 1
Join the two tables on the department ID column to associate employee records with readable department names.
Hint 2
Use a window function like DENSE_RANK() partitioned by the department to calculate the salary rank for each employee.
Hint 3
Wrap the window function in a Common Table Expression (CTE) or subquery so you can filter for ranks less than or equal to 3.
Follow-up questions
- How would you modify the query if you only wanted to return the unique top 3 salary amounts per department, rather than the names of the employees?
- If a department has fewer than 3 employees, how does your current logic handle that? Should it return all of them?
- How would the query change if you needed to calculate the average salary of the top 3 earners in each department?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.