Table: Employee
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| employee_id | int |
| department_id | int |
| primary_flag | varchar |
+---------------+---------+
(employee_id, department_id) is the primary key (combination of columns with unique values) for this table.
employee_id is the id of the employee.
department_id is the id of the department to which the employee belongs.
primary_flag is an ENUM (category) of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. If the flag is 'N', the department is not the primary.
문제설명
직원들은 여러 부서에 소속될 수 있습니다. 직원이 다른 부서에 입사할 때, 그들은 어떤 부서가 그들의 주요 부서인지 결정해야 합니다.
직원이 한 부서에만 소속될 때, 그들의 주요 열은 'N'입니다.
주요 부서와 함께 모든 직원을 보고할 수 있는 해결책을 작성합니다. 한 부서에 속한 직원의 경우 유일한 부서를 보고합니다.
결과표를 순서에 상관없이 반환합니다.
예제
Input:
Employee table:
+-------------+---------------+--------------+
| employee_id | department_id | primary_flag |
+-------------+---------------+--------------+
| 1 | 1 | N |
| 2 | 1 | Y |
| 2 | 2 | N |
| 3 | 3 | N |
| 4 | 2 | N |
| 4 | 3 | Y |
| 4 | 4 | N |
+-------------+---------------+--------------+
Output:
+-------------+---------------+
| employee_id | department_id |
+-------------+---------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
+-------------+---------------+
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(distinct department_id) = 1
)