Primary Department for Each Employee

2pts
Microsoft

Problem Statement

Employees at Microsoft can belong to multiple departments. When an employee is in multiple departments, they must choose one as their primary department, marked with a flag Y. If an employee belongs to only one department, that department is their primary department by default.

Write an SQL query to report all the employees with their primary department.

Rules:

  • For employees belonging to multiple departments, select the row where primary_flag is Y.
  • For employees belonging to only one department, report that specific department even if primary_flag is N.
  • Return the columns: employee_id and department_id.
  • Results must be sorted by employee_id in ascending order.
Tests your understanding of
Basic SQL, Aggregation, UNION and Grouping

Input Tables

employee
employee_id(INTEGER)department_id(INTEGER)primary_flag(ENUM('Y', 'N'))
11N
21N
22Y
33N
42N
43Y
44N

Expected Output

employee_id(INTEGER)department_id(INTEGER)
11
22
33
43

Tags

EasyBasic SQLAggregationUNIONGrouping
10-15 min
62%

Hints