Q. Amber's conglomerate corporation just acquired some new companies. Each of the companies follows this hierarchy:
Founder -> Lead Manager -> Senior Manager -> Manager -> Employee
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:
Input Format
The following tables contain company data:
Cloumn | Type |
---|---|
company_code | String |
founder | String |
Cloumn | Type |
---|---|
lead_manager_code | String |
company_code | String |
Cloumn | Type |
---|---|
senior_manager_code | String |
lead_manager_code | String |
company_code | String |
Cloumn | Type |
---|---|
manager_code | String |
senior_manager_code | String |
lead_manager_code | String |
company_code | String |
Cloumn | Type |
---|---|
employee_code | String |
manager_code | String |
senior_manager_code | String |
lead_manager_code | String |
company_code | String |
Sample Input
Explanation
In company C1, the only lead manager is LM1. There are two senior managers, SM1 and SM2, under LM1. There is one manager, M1, under senior manager SM1. There are two employees, E1 and E2, under manager M1.
In company C2, the only lead manager is LM2. There is one senior manager, SM3, under LM2. There are two managers, M2 and M3, under senior manager SM3. There is one employee, E3, under manager M2, and another employee, E4, under manager, M3.
SELECT
C.company_code,
C.founder,
COUNT(DISTINCT(L.lead_manager_code)),
COUNT(DISTINCT(S.senior_manager_code)),
COUNT(DISTINCT(M.manager_code)),
COUNT(DISTINCT(E.employee_code))
FROM Company C
INNER JOIN Lead_Manager L ON C.company_code = L.company_code
INNER JOIN Senior_Manager S ON L.lead_manager_code = S.lead_manager_code
INNER JOIN Manager M ON S.senior_manager_code = M.senior_manager_code
INNER JOIN Employee E ON M.manager_code = E.manager_code
Group by C.company_code, C.founder
ORDER BY C.company_code
어려운 문제는 아니였지만 오랜만에 혼자힘으로 풀어본 문제이고, 해당 문제는 SELECT와 GROUPBY의 관계를 잘 생각해보고, JOIN을 어떻게 맺을지 생각해 보면 금방 풀 수 있는 문제같다
문제이해를 좀 더 빠르게 하고 원하는 바를 빠르게 캐치하여 문제를 해결하는것에서 만족하지 않고, 좀 더 빠르게 해결방법을 도출하는 연습을 하자!!