41. Top Two Salary Levels per Department
Difficulty: Medium · Topics: Window Functions, Filtering & Selection
Return every employee whose salary is among the two highest distinct salaries in their department. Ties must all be included.
Return department, name, salary.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
employees
| id | name | department | salary |
|---|---|---|---|
| 1 | Asha | Engineering | 90000 |
| 2 | Chitra | Engineering | 90000 |
| 3 | Gita | Engineering | 80000 |
| 4 | Hari | Engineering | 70000 |
| 5 | Ben | Sales | 60000 |
| 6 | Esha | Sales | 55000 |
| 7 | Dev | HR | 40000 |
Expected output
| department | name | salary |
|---|---|---|
| Engineering | Asha | 90000 |
| Engineering | Chitra | 90000 |
| Engineering | Gita | 80000 |
| Sales | Ben | 60000 |
| Sales | Esha | 55000 |
| HR | Dev | 40000 |
Hints
Hint 1
rank() leaves gaps after ties, dense_rank() does not.Hint 2
Rank salaries descending inside each department, then keep ranks 1 and 2.Learn the concepts
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
- filter / where · 5 min read. Keep the rows that match a condition, and the null and operator traps that silently drop data.
PySpark functions you'll practise
- Dense Rank
- Window spec
- filter
- select
- withColumn
- orderBy
Related problems
- Latest Order per Customer · Medium · Window Functions, Filtering & Selection
- Running Total by Region · Medium · Window Functions
- Month-over-Month Change · Medium · Window Functions
- 7-Day Moving Average · Medium · Window Functions
- Customer Spend Quartiles (NTILE) · Medium · Window Functions
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice