[SQL#107]1789. Primary Department for Each Employee

Gi Woon Lee·2024년 8월 16일

SQL

목록 보기
5/33

1789. Primary Department for Each Employee

문제 개요

<employee 테이블>

employee_id - PK
department_id -PK
primary_flag -ENUM( Y or N ) Y means the department is the primary department for the employee


employees can belong to multiple departments
but employees who belong to multiple departments need to decide where is their primary department
.
when an employee belongs to only one department, their primary column is 'N'

Write a solution to report all the employees with their primary department.
For employees who belong to one department, report their only department.

방법1 (배운 점)

  • workfolow
    if count(employee_id) = 1 then print employee_id, department_id
    if count(employee_id) > 1 then print employee_id, department_id where primary_flag is Y

위 work flow를 따라 case when 절로 문제를 해결하려고 했다

select
    case when count(employee_id) = 1 then employee_id, department_id
from employee 
group by employee_id
  • 오류
    The CASE statement is misused; it can't directly return multiple columns like employee_id and department_id

case when은 single value만 한번에 한 번 리턴할 수 있는 점을 공부할 수 있었다.

방법2 (성공!)

  • work flow
  1. primary_flag가 Y인 행 값을 출력한다.
  2. 하나의 department에 속한 사람들만 출력한다.
  3. 두 출력 조건을 where 절에서 or 연산자를 사용하여 연결한다.
    (1번 조건 혹은 2번 조건에 속한 모든 행 출력)
select employee_id, department_id
from employee
where primary_flag = 'Y' or employee_id in (
    select employee_id
    from employee
    group by employee_id
    having count(employee_id) = 1
)

정리:

어렵진 않았지만,
여러 department에 속한 사람들의 primary department는 primary_flag = Y로 표시해놓고
하나의 department에 속한 사람들의 primary department는 primary_flag = N으로 표시해둔 데이터 베이스 구조 탓에 헷갈리는 부분이 있었다.

만약 하나의 department에 속한 사람들의 primary_flag를 Y로 표시해두었다면
(당연히 부서 하나에 속했으니까 그 부서가 primary_department겠지..)

select employee_id, department_id  from employee where primary_flag = 'Y'

한줄로 2초만에 해결되는 문제였다.

데이터 테이블 설계의 중요성을 알게 되었던 문제다.

0개의 댓글