11. Average Salary by Department
Difficulty: Easy · Topics: Aggregations
For each department in employees, return:
departmentavg_salary— the average salary rounded to 2 decimals (null salaries are ignored by the average)headcount— the number of employee rows in the department (including those with a null 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 | 72000 |
| 2 | Ben | Sales | 48000 |
| 3 | Chitra | Engineering | 95000 |
| 4 | Dev | HR | 51000 |
| 5 | Esha | Sales | 52000 |
| 6 | Farah | Engineering | 88001 |
Expected output
| department | avg_salary | headcount |
|---|---|---|
| Engineering | 85000.33 | 3 |
| Sales | 50000 | 2 |
| HR | 51000 | 1 |
Hints
Hint 1
groupBy("department").agg(...) accepts several aggregations at once.Hint 2
Name the outputs with.alias().Hint 3
F.count("*") counts rows; F.count("salary") would skip nulls.Learn the concepts
- 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
- avg
- count
Related problems
- Departments with Large Teams · Easy · Aggregations, Filtering & Selection
- Find Repeat Customers · Easy · Aggregations, Filtering & Selection
- Entry and Exit Pages (MAX_BY / MIN_BY) · Medium · Aggregations
- New Users per Day · Medium · Aggregations
- Conditional Aggregation · Medium · Aggregations, Conditional Logic
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