Leetcode Problem 1731. The Number of Employees Which Report to Each Employee

1731. The Number of Employees Which Report to Each Employee

Leetcode Solutions

Using Self Join to Identify Managers and Aggregate Report Counts and Average Age

Algorithm

  1. Perform a self join on the Employees table by joining the reports_to column of one instance of the table to the employee_id column of another instance.
  2. Select the employee_id and name of the manager from the first instance of the table (aliased as mgr).
  3. Use the COUNT function to count the number of direct reports from the second instance of the table (aliased as emp).
  4. Use the AVG function to calculate the average age of the direct reports, and use the ROUND function to round this average to the nearest integer.
  5. Group the results by the manager's employee_id and name to ensure that we get one row per manager.
  6. Order the results by the manager's employee_id in ascending order.
  7. Ensure that only managers with at least one direct report are included in the final result.

erDiagram
    Employees {
        int employee_id PK "Unique employee identifier"
        varchar name "Employee's name"
        int reports_to "Manager's employee_id (null if no manager)"
        int age "Employee's age"
    }

Using Subquery to Identify Managers and Aggregate Report Counts and Average Age

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...