Study - Problems(IT)/LeetCode - SQL

1731. The Number of Employees Which Report to Each Employee

Dev.D 2024. 11. 27. 22:14

* Problem

For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

Write a solution to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer.

Return the result table ordered by employee_id.

* Explanation

Note that we do not care about days with zero active users.Hercy has 2 people report directly to him, Alice and Bob.
Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest integer.


* Solution (Success)

# Write your MySQL query statement below
SELECT
  Manager.employee_id,
    Manager.name,
      COUNT(Employee.employee_id) AS reports_count,
        ROUND(AVG(Employee.age)) AS average_age
        FROM Employees AS Manager
        INNER JOIN Employees AS Employee
          ON (Employee.reports_to = Manager.employee_id)
          GROUP BY 1
          ORDER BY 1;