SQL Interview Questions – Primary Department for Each Employee

Spread the love

Problem Description –

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.

Problem Link – Primary Department

Difficulty Level – Easy

Solution –

SELECT
    DISTINCT
    employee_id,
    department_id
FROM (
SELECT
    employee_id,
    department_id,
    primary_flag,
    COUNT(department_id) OVER(PARTITION BY employee_id) as total_count
FROM Employee
    ) x
WHERE total_count = 1 OR primary_flag = 'Y'

Rating: 1 out of 5.

Leave a Reply