Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that 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.
(링크)
employee들이 속한 부서가 department_id.
primary_flag가 ‘Y’라면 그 employee에게 primary department라는 뜻
employee들이 여러 부서에 소속될 수 있으며, 반드시 하나는 Primary가 된다
만약 1개의 department에만 소속되었다면 primary_flag가 ‘N’이지만 그게 primary이다
primary department에 들어있는 employee들의 정보만 추출하라
처음 이 문제를 접했을 때는 UNION이나 서브쿼리를 활용해서 풀었다.
이번에 다시 풀면서 번뜩 떠오른 방법이, 어차피 employee_id별로 1개의 row만 추출하면 된다는 것이다
그리고 그 기준은 primary_flag 컬럼.
row_number()를 통해서 partition by employee_id order by primary_flag asc를 해주면
(1) employee_id별 파티션 중 primary_flag가 'Y'인 값이 위로 정렬 => primary department
(2) row가 1개라면 => 어차피 그게 primary department
이를 통해 훨씬 짧은 코드로 답을 도출할 수 있다
SELECT
employee_id
, department_id
FROM
(SELECT
employee_id
, department_id
, row_number() over (partition by employee_id order by primary_flag asc) as 'rn'
FROM
employee
) aa
WHERE
rn = 1
;