Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Have a good contributing!
- [1693. Daily Leads and Partners](./leetcode/easy/1693.%20Daily%20Leads%20and%20Partners.sql)
- [1729. Find Followers Count](./leetcode/easy/1729.%20Find%20Followers%20Count.sql)
- [1741. Find Total Time Spent by Each Employee](./leetcode/easy/1741.%20Find%20Total%20Time%20Spent%20by%20Each%20Employee.sql)
- [1789. Primary Department for Each Employee](./leetcode/easy/1789.%20Primary%20Department%20for%20Each%20Employee.sql)
- [1965. Employees With Missing Information](./leetcode/easy/1965.%20Employees%20With%20Missing%20Information.sql)
- [1978. Employees Whose Manager Left the Company](./leetcode/easy/1978.%20Employees%20Whose%20Manager%20Left%20the%20Company.sql)
- [2356. Number of Unique Subjects Taught by Each Teacher](./leetcode/easy/2356.%20Number%20of%20Unique%20Subjects%20Taught%20by%20Each%20Teacher.sql)
Expand Down
43 changes: 43 additions & 0 deletions leetcode/easy/1789. Primary Department for Each Employee.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Question 1789. Primary Department for Each Employee
Link: https://leetcode.com/problems/primary-department-for-each-employee/description/?envType=study-plan-v2&envId=top-sql-50

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.


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.

Return the result table in any order.
*/

SELECT
e.employee_id,
(CASE
WHEN COUNT(e.employee_id) = 1
THEN (
SELECT e1.department_id
FROM Employee AS e1
WHERE e1.employee_id = e.employee_id
)
ELSE (
SELECT e2.department_id
FROM Employee AS e2
WHERE e2.employee_id = e.employee_id AND e2.primary_flag = 'Y'
)
END) AS department_id
FROM Employee AS e
GROUP BY e.employee_id