← Recursive CTEs

Staff, avg salary with subdepts: branch 2, Jun 30, 2025

Level: Senior200 XP

Instructions

Departments form a tree by departments.parent_id. There are no cycles; the department tree is at most 3 levels deep. Take the top department with id = 2 ('Commerce') and all departments of its subtree (children, their children, and so on; department 2 itself too). For each of these departments, count, over the employees who worked on June 30, 2025 (hired_at not later than this date, and fired_at empty or strictly later), headcount (their number) and avg_salary (their average salary, rounded to 2 decimal places); a department is credited with the employees of itself and of all its subdepartments at any depth. Do not output departments with no such employees together with their subdepartments. Output id, name, headcount, avg_salary. Sort by id ascending.

Hints

Each next one is more detailed and costs more

Log in to open hints

Query

Result

Click Run to see the query result, or Check to submit your solution.

Dataset schema

employees.department_id (0…N) ↔ departments.id (1…1)employees.manager_id (0…N) ↔ employees.id (0…1)departments.parent_id (0…N) ↔ departments.id (0…1)salary_history.employee_id (0…N) ↔ employees.id (1…1)departmentsPKidintegerFKparent_idintegeremployeesPKidintegerFKdepartment_idintegerFKmanager_idintegersalary_historyPKFKemployee_idintegerPKchanged_atdate
Exactly oneZero or oneZero or more
Table relationships
  • N:1Many-to-oneemployees.department_id → departments.id
  • N:1Many-to-oneemployees.manager_id → employees.id
  • N:1Many-to-onedepartments.parent_id → departments.id
  • N:1Many-to-onesalary_history.employee_id → employees.id

Table data

PostgreSQL

Select a table in the diagram or list to view its rows.

Dataset schema