데이터 놀이터
Hackerrank - New Companies 본문
728x90
1. 문제
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.
https://www.hackerrank.com/challenges/the-company/problem?isFullScreen=true
2. 문제 조건
- 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.-> GROUP BY를 통해 COUNT(DINSTINCT ~) 집계함수 활용
- Order your output by ascending company_code. -> ORDER BY
3. 코드 작성
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 AS C
LEFT JOIN Lead_Manager AS L ON L.COMPANY_CODE = C.COMPANY_CODE
LEFT JOIN Senior_Manager AS S ON S.COMPANY_CODE = L.COMPANY_CODE
LEFT JOIN Manager AS M ON M.COMPANY_CODE = S.COMPANY_CODE
LEFT JOIN Employee AS E ON E.COMPANY_CODE = M.COMPANY_CODE
GROUP BY C.COMPANY_CODE, C.founder
ORDER BY C.COMPANY_CODE;
4. 회고
- 테이블의 구조에 대해 다시 한번 생각해볼 기회가 되었다.
- 문제에 따르면 각 테이블 간 계층이 있다. 따라서 단순히 inner join만 한다면 문제가 발생할 수 있다.
- 예를 들어, Senior Manager 하위에 Manager나 Employee가 없다면, INNER JOIN의 경우에는 해당 Senior Manager를 출력하지 않는다. 따라서, LEFT JOIN을 통해서 하위 계층이 없는 경우에도 JOIN을 할 수 있도록 해야한다.
- 계층 간 JOIN에 문제가 발생하지 않도록, 상위 계층에 맞게 LEFT JOIN을 연속적으로 해주어야 한다.
- 문제에 따르면 각 테이블 간 계층이 있다. 따라서 단순히 inner join만 한다면 문제가 발생할 수 있다.
- GROUP BY를 할때, SELECT에서 집계 대상이 아닌 경우에는 GROUP BY 조건에 모두 나열해줘야한다.
728x90
'SQL' 카테고리의 다른 글
SQL 고급 강의 - ERD (0) | 2023.09.22 |
---|---|
SQL 고급 강의 - DML (0) | 2023.09.21 |
우유와 요거트가 담긴 장바구니 (0) | 2023.09.03 |
JOIN - 보호소에서 중성화한 동물 (0) | 2023.08.29 |
JOIN - 상품을 구매한 회원 비율 구하기 (0) | 2023.08.29 |