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.
앰버의 대기없은 몇몇 회사를 인수 했습니다. 각 회사는 다음과 같은 직급 채계를 가집니다. 아래에 주어진 스키마 테이블들을 참고해서 회사 코드, 설립자 이름, 총 매니저 수, 총 리드 매니저 수, 총 시니어 매니저 수, 총 매니저 수, 총 직원수를 쿼리하세요.
참고:
테이블은 중복된 행을 열을 가질 수 있습니다.
회사코드는 문자열이어서 숫자 형태로 정렬되지 않습니다. 가령 회사코드가 C_1, C_2 그리고 C_10이면 회사코드는
C_1, C_10, C_2 순으로 정렬됩니다.
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
JOIN Lead_Manager LM ON C.company_code = LM.company_code
JOIN Senior_Manager SM ON SM.lead_manager_code = LM.lead_manager_code
JOIN Manager M ON M.senior_manager_code = SM.senior_manager_code
JOIN Employee E ON E.manager_code = M.manager_code
GROUP BY C.company_code, C.founder
ORDER BY C.company_code
처음에 모든 조인은 compay_code를 기준으로 했다. 이러면 꼬인다. 이번 관계는 계층 관계기 때문에 순서대로 조인해야 한다.
명심하자 계층 관계는 순서대로 조인하자
<2025년 4월 29일 복습>
SELECT C.company_code, 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
JOIN Lead_Manager LM ON LM.company_code = C.company_code
JOIN Senior_Manager SM ON SM.lead_manager_code = LM.lead_manager_code
JOIN Manager M ON M.senior_manager_code = SM.senior_manager_code
JOIN Employee E ON E.manager_code = M.manager_code
GROUP BY C.company_code, founder
ORDER BY C.company_code ASC;
쓰다보니 기존 코드가 그대로 나왔다. DISTINCT를 쓰는 이유는 조인을 하다보면 겹치는 직원이 있기 마련
'MYSQL > HakerRank_Medium' 카테고리의 다른 글
Weather Observation Station 20(중앙값 구하기) (0) | 2025.04.16 |
---|---|
Weather Observation Station 19, 유클리드 거리 구하기 (0) | 2025.04.16 |
Weather Observation Station 18 (0) | 2025.04.15 |
Binary Tree Nodes (0) | 2025.04.14 |
The PADS (0) | 2025.04.14 |