返回介绍

solution / 0500-0599 / 0570.Managers with at Least 5 Direct Reports / README_EN

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

570. Managers with at Least 5 Direct Reports

中文文档

Description

Table: Employee

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| id      | int   |
| name    | varchar |
| department  | varchar |
| managerId   | int   |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the name of an employee, their department, and the id of their manager.
If managerId is null, then the employee does not have a manager.
No employee will be the manager of themself.

 

Write a solution to find managers with at least five direct reports.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Employee table:
+-----+-------+------------+-----------+
| id  | name  | department | managerId |
+-----+-------+------------+-----------+
| 101 | John  | A      | null    |
| 102 | Dan   | A      | 101     |
| 103 | James | A      | 101     |
| 104 | Amy   | A      | 101     |
| 105 | Anne  | A      | 101     |
| 106 | Ron   | B      | 101     |
+-----+-------+------------+-----------+
Output: 
+------+
| name |
+------+
| John |
+------+

Solutions

Solution 1: Grouping and Joining

We can first count the number of direct subordinates for each manager, and then join the Employee table to find the managers whose number of direct subordinates is greater than or equal to $5$.

import pandas as pd


def find_managers(employee: pd.DataFrame) -> pd.DataFrame:
  # Group the employees by managerId and count the number of direct reports
  manager_report_count = (
    employee.groupby("managerId").size().reset_index(name="directReports")
  )

  # Filter managers with at least five direct reports
  result = manager_report_count[manager_report_count["directReports"] >= 5]

  # Merge with the Employee table to get the names of these managers
  result = result.merge(
    employee[["id", "name"]], left_on="managerId", right_on="id", how="inner"
  )

  # Select only the 'name' column and drop the 'id' and 'directReports' columns
  result = result[["name"]]

  return result
# Write your MySQL query statement below
SELECT name
FROM
  Employee
  JOIN (
    SELECT managerId AS id, COUNT(1) AS cnt
    FROM Employee
    GROUP BY 1
    HAVING cnt >= 5
  ) AS t
    USING (id);

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

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

发布评论

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