返回介绍

solution / 1700-1799 / 1731.The Number of Employees Which Report to Each Employee / README_EN

发布于 2024-06-17 01:03:15 字数 2994 浏览 0 评论 0 收藏 0

1731. The Number of Employees Which Report to Each Employee

中文文档

Description

Table: Employees

+-------------+----------+
| Column Name | Type   |
+-------------+----------+
| employee_id | int    |
| name    | varchar  |
| reports_to  | int    |
| age     | int    |
+-------------+----------+
employee_id is the column with unique values 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). 

 

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.

The result format is in the following example.

 

Example 1:

Input: 
Employees table:
+-------------+---------+------------+-----+
| employee_id | name  | reports_to | age |
+-------------+---------+------------+-----+
| 9       | Hercy   | null     | 43  |
| 6       | Alice   | 9      | 41  |
| 4       | Bob   | 9      | 36  |
| 2       | Winston | null     | 37  |
+-------------+---------+------------+-----+
Output: 
+-------------+-------+---------------+-------------+
| employee_id | name  | reports_count | average_age |
+-------------+-------+---------------+-------------+
| 9       | Hercy | 2       | 39      |
+-------------+-------+---------------+-------------+
Explanation: 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.

Solutions

Solution 1: Self-Join + Grouping

We can use self-join to connect the information of each employee's superior manager to the information of each employee, and then use grouping and aggregation to count the number of subordinates and the average age of each manager.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文