Skip to content

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

idnamedepartmentsalary
1AshaEngineering90000
2ChitraEngineering90000
3GitaEngineering80000
4HariEngineering70000
5BenSales60000
6EshaSales55000
7DevHR40000

Expected output

departmentnamesalary
EngineeringAsha90000
EngineeringChitra90000
EngineeringGita80000
SalesBen60000
SalesEsha55000
HRDev40000

Hints

Hint 1rank() leaves gaps after ties, dense_rank() does not.
Hint 2Rank salaries descending inside each department, then keep ranks 1 and 2.

Learn the concepts

PySpark functions you'll practise

Related problems

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