You are given an Employee table that tracks which departments employees belong to and whether each department is their primary department.
Key Rules:
- Employees can belong to multiple departments
- When an employee belongs to multiple departments, exactly one has
primary_flag = 'Y' - When an employee belongs to only one department, that department has
primary_flag = 'N'
Write a SQL query to find each employee's primary department. For employees with multiple departments, return the one marked as primary. For employees with only one department, return that department.
Table Schema
| Column Name | Type | Description |
|---|---|---|
employee_id
PK
|
int | Unique identifier for the employee |
department_id
PK
|
int | Identifier for the department |
primary_flag
|
varchar | Either 'Y' (primary) or 'N' (not primary) |
Input & Output
| 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 |
| employee_id | department_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
Employee 1: Only in department 1, so return department 1 (even though primary_flag='N')
Employee 2: In departments 1 and 2, department 1 has primary_flag='Y', so return department 1
Employee 3: Only in department 3, so return department 3
Employee 4: In departments 2, 3, and 4, department 3 has primary_flag='Y', so return department 3
| employee_id | department_id | primary_flag |
|---|---|---|
| 1 | 1 | N |
| 2 | 2 | N |
| 3 | 3 | N |
| employee_id | department_id |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
All employees belong to only one department each. Even though all have primary_flag='N', we return their single department as their primary department.
| employee_id | department_id | primary_flag |
|---|---|---|
| 1 | 1 | Y |
| 1 | 2 | N |
| 2 | 2 | N |
| 2 | 3 | Y |
| employee_id | department_id |
|---|---|
| 1 | 1 |
| 2 | 3 |
Both employees belong to multiple departments. Employee 1's primary is department 1, Employee 2's primary is department 3 (marked with primary_flag='Y').
Constraints
-
1 ≤ employee_id ≤ 100 -
1 ≤ department_id ≤ 100 -
primary_flagis either'Y'or'N' -
Each employee has at most one department with
primary_flag = 'Y' -
Employees with only one department always have
primary_flag = 'N'