SQL 스터디/HackerRank

[해커랭크] MySQL JOIN - New Companies

황금붕어빵 2023. 9. 12. 07:00

 


 

 

New Companies | HackerRank

Find total number of employees.

www.hackerrank.com

이번 문제는 JOIN과 계산함수를 활용하는 문제입니다.

 

Amber's conglomerate corporation just acquired some new companies. Each of the companies follows this hierarchy: 

Given the table schemas below, write a query to print the company_code, founder name, total number of lead managers, total number of senior managers, total number of managers, and total number of employees. Order your output by ascending company_code.

Note:
 * The tables may contain duplicate records.
 * The company_code is string, so the sorting should not be numeric. For example, if the company_codes are C_1, C_2, and C_10, then the ascending company_codes will be C_1, C_10, and C_2.

문제는 회사의 code와 설립자 이름, 리드매니저의 수, 시니어매니저의 수, 매니저의 수, 직원의 수를 출력합니다.

 

총 5개의 테이블이 있으며 각 테이블 마다 상위 직책에 대한 정보가 모두 포함되어 있습니다. 

select c.company_code
     , c.founder
     , count(distinct lm.lead_manager_code)
     , count(distinct sm.senior_manager_code)
     , count(distinct m.manager_code)
     , count(distinct e.employee_code)
from company c
     left join lead_manager lm on c.company_code = lm.company_code
     left join senior_manager sm on lm.lead_manager_code = sm.lead_manager_code
     left join manager m on sm.senior_manager_code = m.senior_manager_code
     left join employee e on m.manager_code = e.manager_code
group by 1, 2
order by 1

처음에는 company 테이블과 employee 테이블만 JOIN을 하려고 했으나 직원 테이블에는 데이터가 없지만 아래 직원이 없는 매니저나 시니어 매니저가 있을 수고 있다고 판단하여 모든 테이블에 JOIN을 하였습니다.

 

그리고 LEFT JOIN을 통해 모든 직원을 출력할 수 있습니다.

 

GROUP BY를 활용해서 각 회사 별로 각 직책 별 직원 수를 계산하고 중복 제거를 위해서 distinct를 사용했습니다.