Identifying Primary Departments for Employees in SQL
To identify an employee's primary department, you must handle two distinct scenarios based on the input data:
- If an employee is assigned to multiple departments, retrieve the record where
primary_flagis set to 'Y'. - If an employee is assigned to only one department, retrieve that record regardless of the
primary_flagvalue.
Approach 1: Using the UNION Operator
The UNION operator combines result sets from multiple queries. By splitting the logic into two separate sub-queries, we can cleanly extract the required data points:
SELECT employee_id, department_id
FROM Employees
GROUP BY employee_id
HAVING COUNT(employee_id) = 1
UNION
SELECT employee_id, department_id
FROM Employees
WHERE primary_flag = 'Y';
This method ensures that single-department employees are caught by the first query, while primary departments for multi-department employees are caught by the second, all while automatically removing duplicates.
Approach 2: Using Window Functions
Window functions allow you to perform calculations across a set of table rows that are related to the current row without collapsing them into a single output row. By using COUNT() OVER(), we can calculate the total number of departments per employee while keeping the individual row details accessible.
SELECT employee_id, department_id
FROM (
SELECT
employee_id,
department_id,
primary_flag,
COUNT(*) OVER (PARTITION BY employee_id) AS total_depts
FROM Employees
) AS subquery
WHERE total_depts = 1 OR primary_flag = 'Y';
In this solution:
PARTITION BY employee_idensures the count is specific to each worker.- The outer query filters the result set to include only those rows that satisfy your business logic, efficiently avoiding the need for complex joins or temporary tables.