내 코드
SELECT e.reports_to AS employee_id ,
(SELECT name FROM Employees WHERE employee_id = e.reports_to) AS name,
COUNT(e.reports_to) AS reports_count,
round(avg(e.age)) AS average_age
FROM Employees e
GROUP BY e.reports_to
HAVING e.reports_to IS NOT NULL
ORDER BY employee_id
정답은 나왔지만 내가 짠 쿼리의 Runtime이
하위 10%에 들어간다고 나왔다. 나도 짜면서도 더 좋은 방법이 있지 않을까 고민이 많았는데 역시 문제가 있었다.
수정해본 코드
SELECT reports_to AS employee_id ,
(SELECT e.name FROM Employees e WHERE e.employee_id = reports_to) AS name,
COUNT(reports_to) AS reports_count,
round(avg(age)) AS average_age
FROM Employees
GROUP BY reports_to
HAVING reports_to IS NOT NULL
ORDER BY employee_id
e.name , e.employee 등 참조가 많아서 코드가 느려지는 것으로 예상하고
메인 쿼리에 참조를 빼고 서브쿼리에만 넣어서 구분을 하려고 했다.
이론상 되지 않을까? 였는데 OUTPUT에서 이름 부분에 NULL 이 나와서 당황했다. 같은 코드인 줄 알았건만..
이유는 차차 알아보도록 하고..
SELECT e.reports_to AS employee_id,
mgr.name AS name,
COUNT(e.reports_to) AS reports_count,
ROUND(AVG(e.age)) AS average_age
FROM Employees e
JOIN Employees mgr ON e.reports_to = mgr.employee_id
WHERE e.reports_to IS NOT NULL
GROUP BY e.reports_to, mgr.name
ORDER BY employee_id;
JOIN을 사용해보도록 했다.