본문 바로가기

SQL/LeetCode

[SQL] LeetCode: 1731. The Number of Employees Which Report to Each Employee

1731. The Number of Employees Which Report to Each Employee

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

[문제]

 

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.

 

 

[풀이]

-- 1. 출력: 매니저 아이디와 이름, 부하직원 수, 부하직원 평균 나이(반올림) 
-- 2. 필터: 부하지원 1명 이상인 매니저
-- 3. 정렬: employee_id(매니저 아이디)

SELECT e1.employee_id 
      ,e1.name
      ,COUNT(e2.reports_to) AS reports_count
      ,ROUND(AVG(e2.age)) AS average_age
FROM employees e1 
   LEFT JOIN employees e2 ON e1.employee_id = e2.reports_to
GROUP BY e1.employee_id
HAVING COUNT(e2.reports_to) >= 1
ORDER BY e1.employee_id

 

 

다른 풀이를 보니까 INNER JOIN을 써서 HAVING절 없이 푸는 방법도 있었다.

그런데 부하직원(reports_to하는 직원)이 없는 직원을 조회하고 싶을 때는 위와 같은 쿼리가 활용하기 쉬울 것 같다.

JOIN 조건을 바꿀 필요없이 HAING절에서 조건만 변경하면 되니까 말이다. ( HAVING COUNT(e2.reports_to) = 0)

(더 좋은 방법이 있을 수도! 아시는 분은 댓글로 알려주세용:)

단순히 문제만 풀기보다는 다양한 상황에서 활용할 수 있는 쿼리 짜는 연습을 꾸준히 해보자!