Skip to content

Headcount by level below the CEO

HardFull bankCTEs and subqueriesSelf joins20 min2 hidden datasets

The task

The people team wants to know how deep the reporting line goes. The CEO is the one employee with no manager_id. Level 1 is everyone who reports directly to the CEO, level 2 is everyone who reports to a level 1 person, and so on. The CEO is not on any level.

For each level, count the current employees (no termination_date) and average their salary. A person who has left still sits in the reporting line, so the people who report to them stay on the level where the line puts them.

Return level, headcount and avg_salary (rounded to 2 decimal places), one row per level that has at least one current employee, sorted by level.

Expected output

levelheadcountavg_salary
  • Sorted by level ascending.
  • Numbers rounded to 2 decimal places.
  • Checked on the sample and on 2 hidden datasets. How grading works

Tables People team · click a name to insert it

departments7 rows in the sample

One row per department. Key: department_id.

intUnique id.
textName.
textMain office city.
employees120 rows in the sample

Everyone who has worked here, including people who left. Key: employee_id.

intUnique id.
textName.
intDepartment. NULL for a few people between teams.
intTheir manager (an employee_id). NULL for the CEO.
textTitle.
dateFirst day.
dateLast day. NULL while employed.
numeric(10,2)Current (or final) yearly salary, USD.
salary_changes367 rows in the sample

Every salary someone has had, from the day it applied. Key: employee_id, effective_on.

intThe employee.
dateFirst day of this salary.
numeric(10,2)Yearly salary, USD.
reviews301 rows in the sample

Year-end review ratings. Key: employee_id, review_year.

intThe employee.
intYear reviewed.
int1 (low) to 5 (high).

Related questions

Loading the editor and PostgreSQL