570. Managers with at Least 5 Direct Reports


Posted by ikl258794613 on 2024-02-22

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

解答:

SELECT emplA.name 
FROM Employee emplA
INNER JOIN Employee emplB  ON emplA.id = emplB.managerId
GROUP BY emplB.managerId
HAVING COUNT(emplB.managerId) >= 5

HAVING 子句是用來取代 WHERE 搭配聚合函數 (aggregate function) 進行條件查詢,因為 WHERE 不能與聚合函數一起使用。

第一次寫的sql

SELECT e.name 
FROM Employee e
WHERE COUNT(e.managerId = e.id) >= 5

明顯犯下 WHERE 不能與聚合函數一起使用。

解題思路:
先下這段sql會發現emplA.managerId 是NULL ,所以GROUP BY時用emplB.managerId
然後條件也要用HAVING COUNT(emplB.managerId) >= 5

SELECT *
FROM Employee emplA
INNER JOIN Employee emplB  ON emplA.id = emplB.managerId
id name department managerId id name department managerId
101 John A null 102 Dan A 101
101 John A null 103 James A 101
101 John A null 104 Amy A 101
101 John A null 105 Anne A 101
101 John A null 106 Ron B 101

#SQL







Related Posts

MTR04_0818

MTR04_0818

相見恨晚的 chrome 插件 — Octotree - GitHub code tree

相見恨晚的 chrome 插件 — Octotree - GitHub code tree

[評價] 羅技鍵鼠組 MK240 NANO (K240+M212)

[評價] 羅技鍵鼠組 MK240 NANO (K240+M212)


Comments