2023年9月13日 星期三

9/13 每日一題(MYSQL 列出被回報的所有id)

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). 

 

For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

Write an SQL query 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 query 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.


 # Write your MySQL query statement below

SELECT E1.employee_id , E1.name, COUNT(E2.reports_to) AS reports_count , ROUND(AVG(E2.age)) AS average_age
FROM Employees E1
join Employees E2 on E1.employee_id  = E2.reports_to
GROUP BY employee_id
HAVING reports_count > 0  #避免只有NULL時, 所以限定在0以上
order by employee_id


-------------------------------------------------------
SELECT 
    mgr.employee_id,
    mgr.name,
    COUNT(e.employee_id) as reports_count,
    ROUND(AVG(e.age), 0) as average_age

FROM 
    (SELECT DISTINCT employee_id, name 
    FROM Employees WHERE employee_id 
    IN (SELECT reports_to FROM Employees WHERE reports_to IS NOT NULL)) as mgr

JOIN
    Employees e ON e.reports_to = mgr.employee_id

GROUP BY
    mgr.employee_id, mgr.name
ORDER BY employee_id


-------------------------------------------------------------------

SELECT employee_id, name, reports_count, average_age
FROM Employees e
JOIN
(SELECT reports_to, count(employee_id) AS reports_count, round(avg(age),0) AS average_age
FROM Employees
GROUP BY reports_to
HAVING count(employee_id)>=1) a
ON e.employee_id = a.reports_to
ORDER BY employee_id


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁