반응형

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.

 

 

  • reports_to는 누구에게 보고하는지를 나타냅니다
  • null이면 보고하는 사람이 없는 것, 즉 최상위 직원일 수 있습니다
  • 이 문제에서는 직원을 최소 한 명 이상 직접 보고받는 사람 매니저로 정의합니다

보고하는 직원과 매니저를 연결하기 (self join)

select *
from employees e1 join employees e2 
on e1.employee_id = e2.reports_to 
  
| employee_id | name  | reports_to | age | employee_id | name  | reports_to | age |
| ----------- | ----- | ---------- | --- | ----------- | ----- | ---------- | --- |
| 9           | Hercy | null       | 43  | 6           | Alice | 9          | 41  |
| 9           | Hercy | null       | 43  | 4           | Bob   | 9          | 36  |

매니저별로 그룹화해서 직원 수와 평균 나이 구하기

select 
	e1.employee_id, 
    e1.name, 
    count(*) 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 e1.employee_id
order by e1.employee_id

| employee_id | name  | reports_count | average_age |
| ----------- | ----- | ------------- | ----------- |
| 9           | Hercy | 2             | 39          |

 

반응형
올리브한입