Leecode_SQL50_570. Managers with at Least 5 Direct Reports

发布于:2024-10-10 ⋅ 阅读:(117) ⋅ 点赞:(0)

Leecode

  1. Managers with at Least 5 Direct Reports

Problem 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

My solution

WITH a AS(
    SELECT m.name, COUNT(e.managerId) AS coun
    FROM Employee e
        JOIN Employee m
            ON e.managerId = m.id
    GROUP BY e.managerId
)
SELECT a.name
FROM a
WHERE coun >= 5

My failed solution, test case not passed when name=null:

# Write your MySQL query statement below
WITH a AS (
    SELECT COUNT(id) AS count_connected, managerId
    FROM Employee e
    GROUP BY managerId
    HAVING COUNT(name) >= 5
)
SELECT e.name
FROM a
    JOIN Employee e
        ON a.managerId = e.id


网站公告

今日签到

点亮在社区的每一天
去签到