Employees in Unique Department

Easy

Description

Write a SQL query to find employees who work in departments with only one employee. Return employee_id.

Table:employees
ColumnType
employee_idINT
department_idINT

Examples

Input:CREATE TABLE employees (employee_id INT, department_id INT); INSERT INTO employees VALUES (1, 1), (2, 1), (3, 2);
Output:3
Explanation:

Employees 1 and 2 are both in department 1, so neither qualifies. Employee 3 is alone in department 2, so they are returned.

Input:CREATE TABLE employees (employee_id INT, department_id INT); INSERT INTO employees VALUES (101, 10), (102, 20), (103, 20), (104, 30), (105, 30), (106, 40);
Output:101, 106
Explanation:

Employee 101 is the only one in department 10, and employee 106 is the only one in department 40. Departments 20 and 30 each have 2 employees, so those employees are excluded.

Input:CREATE TABLE employees (employee_id INT, department_id INT); INSERT INTO employees VALUES (5, 100), (6, 200), (7, 200), (8, 200), (9, 300), (10, 400), (11, 400);
Output:5, 9
Explanation:

Employee 5 is alone in department 100 and employee 9 is alone in department 300. Department 200 has 3 employees and department 400 has 2 employees, so those don't qualify as unique departments.

Constraints

  • Use GROUP BY with HAVING COUNT = 1

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!