Coding
Quant Python

Teammates Under One Manager in SQL

Difficulty

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

HR wants a list of every pair of colleagues who report to the same manager, to plan who covers for whom. People who have left the firm stay in the table with an end date, and they must not appear in a pair.

load_employees(rows) is already written. It builds an in-memory SQLite database with one table:

CREATE TABLE employees (
    employee_id INTEGER PRIMARY KEY,
    first_name  TEXT NOT NULL,
    last_name   TEXT NOT NULL,
    manager_id  INTEGER,   -- NULL at the top of the tree
    end_date    TEXT       -- NULL while employed, else 'YYYY-MM-DD'
)

Write the query in employee_pairs(conn). Return one row

(manager_id, manager_name, employee_1_id, employee_1_name, employee_2_id, employee_2_name)

for every pair of current employees (end_date IS NULL) with the same manager_id:

  • Each name is first_name || ' ' || last_name.
  • Each pair appears once, with employee_1_id < employee_2_id.
  • The end date filter applies to the two employees only. A manager who has left still heads the pairs of the people who report to them.
  • Employees with a NULL manager_id have no manager, so they form no pairs.

Order the rows by manager_id, then employee_1_id, then employee_2_id.

Example

employee_pairs(load_employees([
    (1, "Ava", "Reed", None, None),
    (16, "Noah", "Patel", 1, None),
    (30, "Ethan", "Brooks", 1, "2025-11-30"),
    (21, "Mia", "Chen", 16, None),
    (22, "Liam", "Okafor", 16, None),
    (25, "Zoe", "Varga", 16, None),
    (40, "Omar", "Haddad", 22, None),
]))
# [(16, 'Noah Patel', 21, 'Mia Chen', 22, 'Liam Okafor'),
#  (16, 'Noah Patel', 21, 'Mia Chen', 25, 'Zoe Varga'),
#  (16, 'Noah Patel', 22, 'Liam Okafor', 25, 'Zoe Varga')]

Noah's three reports make three pairs. Ava's reports are Noah and Ethan, but Ethan has left, so Ava heads no pair. Liam has one report, which is not enough for a pair.

Constraints

  • Up to 60,000 employees. The judge runs SQLite in your browser.
  • Every manager_id that is not NULL is the employee_id of a row in the table. Nobody is their own manager.
  • You could compute the answer in Python from the raw rows, but the point is the query: the reference solution is one SQL statement.
Rate this problem
Language: Python 3.12employee_pairs
Rate this problem