Skip to content

Commit aaac1bd

Browse files
authored
Merge pull request #16 from iamAntimPal/Branch-1
Create 1789. Primary Department for Each Employee.sql
2 parents 5e868b2 + 9af7a3e commit aaac1bd

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
1789. Primary Department for Each Employee
2+
3+
4+
+---------------+---------+
5+
| Column Name | Type |
6+
+---------------+---------+
7+
| employee_id | int |
8+
| department_id | int |
9+
| primary_flag | varchar |
10+
+---------------+---------+
11+
(employee_id, department_id) is the primary key (combination of columns with unique values) for this table.
12+
employee_id is the id of the employee.
13+
department_id is the id of the department to which the employee belongs.
14+
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.
15+
16+
17+
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'.
18+
19+
Write a solution to report all the employees with their primary department. For employees who belong to one department, report their only department.
20+
21+
Return the result table in any order.
22+
23+
The result format is in the following example.
24+
25+
26+
27+
Example 1:
28+
29+
Input:
30+
Employee table:
31+
+-------------+---------------+--------------+
32+
| employee_id | department_id | primary_flag |
33+
+-------------+---------------+--------------+
34+
| 1 | 1 | N |
35+
| 2 | 1 | Y |
36+
| 2 | 2 | N |
37+
| 3 | 3 | N |
38+
| 4 | 2 | N |
39+
| 4 | 3 | Y |
40+
| 4 | 4 | N |
41+
+-------------+---------------+--------------+
42+
Output:
43+
+-------------+---------------+
44+
| employee_id | department_id |
45+
+-------------+---------------+
46+
| 1 | 1 |
47+
| 2 | 1 |
48+
| 3 | 3 |
49+
| 4 | 3 |
50+
+-------------+---------------+
51+
Explanation:
52+
- The Primary department for employee 1 is 1.
53+
- The Primary department for employee 2 is 1.
54+
- The Primary department for employee 3 is 3.
55+
- The Primary department for employee 4 is 3.
56+
57+
58+
# Write your MySQL query statement below
59+
SELECT
60+
employee_id,
61+
department_id
62+
FROM Employee
63+
WHERE primary_flag = 'Y'
64+
UNION DISTINCT
65+
SELECT
66+
employee_id,
67+
department_id
68+
FROM Employee
69+
GROUP BY 1
70+
HAVING COUNT(*) = 1;

0 commit comments

Comments
 (0)