Formatted question description: https://leetcode.ca/all/1731.html

1731. The Number of Employees Which Report to Each Employee

Level

Easy

Description

Table: Employees

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| employee_id | int      |
| name        | varchar  |
| reports_to  | int      |
| age         | int      |
+-------------+----------+
employee_id is the primary key for this table.
This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null). 

Write an SQL query to report the ids and the names of the people that other employees reported to (excluding null values), the number of employees who report to them, and the average age of those members rounded to the nearest integer.

Return the result table ordered by employee_id.

The query result format is in the following example:

Employees table:
+-------------+---------+------------+-----+
| employee_id | name    | reports_to | age |
+-------------+---------+------------+-----+
| 9           | Hercy   | null       | 43  |
| 6           | Alice   | 9          | 41  |
| 4           | Bob     | 9          | 36  |
| 2           | Winston | null       | 37  |
+-------------+---------+------------+-----+

Result table:
+-------------+-------+---------------+-------------+
| employee_id | name  | reports_count | average_age |
+-------------+-------+---------------+-------------+
| 9           | Hercy | 2             | 39          |
+-------------+-------+---------------+-------------+
Alice and Bob report to Hercy, hence Hercy has 2 people report to him, and the average of their age is (41+36)/2 = 38.5 which is 39 after rounding it to the nearest integer.

Solution

First, find the people that other employees report to, remove null values, and calculate the values of reports_count and average_age. Next, use left join to obtain the names.

# Write your MySQL query statement below
select e1.employee_id, name, reports_count, average_age
    from (
        select reports_to as employee_id, count(distinct employee_id) as reports_count,
            round(avg(age)) as average_age
            from Employees
            group by reports_to
            having reports_to is not null
    ) e1
    left join Employees e2
    on e1.employee_id = e2.employee_id
    order by e1.employee_id;

All Problems

All Solutions