본문 바로가기
일일 문제 풀이/HackerRank

[SQL] 해커랭크 HackerRank New Companies 문제 풀이

by 엘리는 코딩 마스터 2025. 3. 15.

 

해커랭크
문제
문제
문제
예시

 

문제

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.

 

해석

Amber의 대기업이 여러 회사를 인수했으며, 각 회사는 특정한 조직 계층 구조(hierarchy)를 따르고 있음.

 

요구 사항

주어진 테이블을 이용하여 각 회사별로 다음 정보를 출력하는 SQL 쿼리를 작성해야 함:

  1. company_code (회사 코드)
  2. founder (회사의 창립자 이름)
  3. lead managers의 총 수
  4. senior managers의 총 수
  5. managers의 총 수
  6. employees의 총 수

출력 결과는 company_code 기준으로 알파벳순 정렬해야 함.
➡ company_code가 숫자가 아닌 문자열이므로, 정렬할 때 C_1, C_10, C_2가 아니라 C_1, C_2, C_10 순서여야 함.

 

정답

처음 쿼리

select distinct c.company_code, c.Founder, count(distinct l.lead_manager_code), count(distinct s.senior_manager_code), count(distinct e.employee_code)
from Company c 
join Lead_Manager l using(company_code) 
join Senior_Manager s using(company_code) 
join Manager m using(company_code)
join Employee e using(company_code)
group by c.company_code, c.Founder
order by 1;

 

처음에 문제 풀때 모든 테이블에 join을 걸음

중복될 가능성이 있음

 

서브쿼리를 활용해서 풀어보기로 함

SELECT c.company_code, 
       c.founder, 
       (SELECT COUNT(DISTINCT l.lead_manager_code) FROM Lead_Manager l WHERE l.company_code = c.company_code) AS total_lead_managers,
       (SELECT COUNT(DISTINCT s.senior_manager_code) FROM Senior_Manager s WHERE s.company_code = c.company_code) AS total_senior_managers,
       (SELECT COUNT(DISTINCT m.manager_code) FROM Manager m WHERE m.company_code = c.company_code) AS total_managers,
       (SELECT COUNT(DISTINCT e.employee_code) FROM Employee e WHERE e.company_code = c.company_code) AS total_employees
FROM Company c
ORDER BY 1;

 

배운 점

  • join을 복합으로 사용하면 성능면에서도 그렇고 중복으로 데이터가 겹치기에 좋은 판단이 아니다
  • 이럴 경우 서브쿼리를 적극 활용하자
  • where from 테이블과 서브쿼리의 code가 같다는 조건을 걸어서 진행하면 좋다.