Agent reporting chain

hardSQL~30 min · 4 tests · helpdesk

HR is reorganising the help desk and wants every agent’s full line of command.

In agents, manager_id points at the agent’s manager. Agents with a NULL manager_id are at the top. Today every chain is short, but the org is about to get deeper, so your query must handle chains of any length. You can assume there are no cycles.

Return one row per agent:

column type meaning
agent_id integer the agent
name text the agent’s name
depth integer 0 for a top manager, 1 for someone reporting to one, and so on
top_manager_id integer the agent_id at the top of this agent’s chain (themselves if depth is 0)
chain text agent ids from the top down to this agent, joined with ' > ', e.g. '1 > 4'

A top manager’s chain is just their own id, like '1'.

Row order doesn’t matter.

Tables: agents.

solution.sqlDuckDB · helpdesk

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run