KEEP GOING

[MySQL] HackerRank : New Companies Solution 본문

code review/sql

[MySQL] HackerRank : New Companies Solution

jmHan 2021. 12. 20. 18:44
반응형

https://www.hackerrank.com/challenges/the-company/problem

 

New Companies | HackerRank

Find total number of employees.

www.hackerrank.com

 

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.

 

 

1. 잘못된 풀이 (에러 발생)

SELECT C.company_code
      ,C.founder
      ,COUNT(DISTINCT E.lead_manager_code)
      ,COUNT(DISTINCT E.senior_manager_code)
      ,COUNT(DISTINCT E.manager_code)
      ,COUNT(DISTINCT E.employee_code)
FROM Company C 
    INNER JOIN Employee E ON C.company_code = E.company_code
GROUP BY C.company_code
ORDER BY C.company_code

ERROR 1055 (42000) at line 8: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'run_6enugxjfkd0.C.founder' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

 

Company 테이블의 founder는 그룹화 대상이 아니지만 조회할 목록 중 하나이다. founder 컬럼에 접근하기 위해서는 GROUP BY 절에 founder 컬럼을 따로 추가해주어야 한다. 

 

 

2. 잘못된 풀이 (정답 처리되나 정답이 아닌 코드)

SELECT C.company_code
      ,C.founder
      ,COUNT(DISTINCT E.lead_manager_code)
      ,COUNT(DISTINCT E.senior_manager_code)
      ,COUNT(DISTINCT E.manager_code)
      ,COUNT(DISTINCT E.employee_code)
FROM Company C 
    INNER JOIN Employee E ON C.company_code = E.company_code
GROUP BY C.company_code, C.founder
ORDER BY C.company_code

위 풀이에서 발생한 오류를 해결했지만 마찬가지로 정답이 아닌 코드이다. 

이러한 방식으로 접근하하면 employee를 가지고 있지 않는 manager에 대한 데이터에 관해서는 오답으로 처리된다.

즉, 해당 사이트에서 제공해주는 데이터 파일에는 해당 에러를 컨트롤할 test case가 없으므로 정답인 코드로 인정되는 것이다.

 

                                   Senior_Manager Table: 

예시에서 들어준 Senior_Manager 테이블을 보면 SM2는 manager를 가지고 있지 않기 때문에 Employee 테이블에서도 나타나고 있지 않다. 이러한 문제를 해결하기 위해서는 모든 테이블을 JOIN하여 문제를 해결해야 한다.

 

 

3. 정답인 코드

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 C.company_code, C.founder
ORDER BY C.company_code
반응형
Comments