Organizational structures are often hierarchical, and analyzing these relationships is a common task in enterprise software. "The Number of Employees Which Report to Each Employee" is a database problem where you are given an employees table containing IDs, names, and the IDs of their managers. Your task is to identify all managers (employees who have at least one other employee reporting to them) and for each manager, report their ID, name, the number of direct reports they have, and the average age of those reports rounded to the nearest integer.
This the Number of Employees Which Report to Each Employee interview question is frequently asked by companies like Microsoft and Amazon. It tests your ability to perform self-joins or correlated subqueries in SQL. It also evaluates your proficiency with aggregation and rounding functions. Understanding how to navigate a parent-child relationship within a single table is a fundamental skill for managing relational data in business applications.
This problem follows the Database interview pattern, specifically focusing on self-referential relationships.
mgr) represents the managers, and the other alias (e.g., emp) represents the subordinates.mgr.employee_id = emp.reports_to.mgr.employee_id and mgr.name.COUNT(emp.employee_id) to get the number of reports and ROUND(AVG(emp.age)) to calculate the average age.Employees Table:
In "The Number of Employees Which Report to Each Employee coding problem," a common mistake is using the manager's age in the average calculation instead of the subordinates' ages. Another error is not rounding the average age correctly or using an incorrect join type that fails to filter out employees who aren't managers.
Practice working with recursive data structures in SQL. Self-joins are the most common way to handle hierarchies, but some databases also support recursive Common Table Expressions (CTEs), which are useful for deeper hierarchical analysis. Always be careful about which table alias you are pulling data from during a self-join.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Fix Names in a Table | Easy | Solve | |
| Not Boring Movies | Easy | Solve | |
| Primary Department for Each Employee | Easy | Solve | |
| Queries Quality and Percentage | Easy | Solve | |
| Combine Two Tables | Easy | Solve |