17. Median and 90th Percentile
Difficulty: Medium · Topics: Aggregations
Per dept, compute median_salary (exact median: average of the two middle values for an even count) and p90_salary (percentile_approx at 0.9, which returns an actual salary from the data).
Missing salaries are ignored. Return dept, median_salary, p90_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
| dept | salary |
|---|---|
| eng | 100 |
| eng | 200 |
| eng | 300 |
| eng | 400 |
| ops | 50 |
| ops | 70 |
| ops | 90 |
Expected output
| dept | median_salary | p90_salary |
|---|---|---|
| eng | 250 | 400 |
| ops | 70 | 90 |
Hints
Hint 1
F.median("salary") (Spark 3.4+) interpolates between the middle values.Hint 2
F.percentile_approx("salary", 0.9) picks a real value: the smallest salary with at least 90% of values at or below it.Hint 3
Both skip nulls.Learn the concepts
- percentile_approx · 4 min read. Medians and p90s that scale to billions of rows, and how the accuracy setting trades memory for error.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
PySpark functions you'll practise
- groupBy
- agg
- median
- percentile_approx
Related problems
- Conditional Aggregation · Medium · Aggregations, Conditional Logic
- Entry and Exit Pages (MAX_BY / MIN_BY) · Medium · Aggregations
- New Users per Day · Medium · Aggregations
- Average Salary by Department · Easy · Aggregations
- Departments with Large Teams · Easy · Aggregations, Filtering & Selection
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