Primary Department For Each Employee Problem
Description
LeetCode Problem 1789.
Table: Employee
1
2
3
4
5
6
7
8
9
10
11
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| employee_id | int |
| department_id | int |
| primary_flag | varchar |
+---------------+---------+
(employee_id, department_id) is the primary key 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 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.
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 an SQL query to report all the employees with their primary department. For employees who belong to one department, report their only department.
Return the result table in any order.
The query result format is in the following example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 |
+-------------+---------------+--------------+
Result table:
+-------------+---------------+
| employee_id | department_id |
+-------------+---------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
+-------------+---------------+
- The Primary department for employee 1 is 1.
- The Primary department for employee 2 is 1.
- The Primary department for employee 3 is 3.
- The Primary department for employee 4 is 3.
MySQL Solution
1
2
3
4
5
6
7
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(department_id) = 1)
LeetCode Database - Easy
LeetCode 1407
LeetCode 1435
LeetCode 1484
LeetCode 1495
LeetCode 1511
LeetCode 1517
LeetCode 1527
LeetCode 1543
LeetCode 1565
LeetCode 1571
LeetCode 1581
LeetCode 1587
LeetCode 1607
LeetCode 1623
LeetCode 1633
LeetCode 1661
LeetCode 1667
LeetCode 1677
LeetCode 1683
LeetCode 1693
LeetCode 1729
LeetCode 1731
LeetCode 1741
LeetCode 1757
LeetCode 1777
LeetCode 1789
LeetCode 1795
LeetCode 1809
More LeetCode Database
MySQL Tutorials