Starting with a basic Employee/Supervisor Hierarchy, I am using recursive CTE to build out the levels:
WITH EmployeeSupervisor
AS (
SELECT *
FROM (
VALUES ('mike','lisa')
,('kevin','lisa')
,('lisa','ken')
,('ken','scott')
,('scott','chris')
,('chris','')
) RawData(emp, sup)
)
,Hier
AS (
-- anchor level, no supervisor
SELECT 1 AS lvl
,emp
,sup
FROM EmployeeSupervisor
WHERE sup = ''
UNION ALL
-- recursive member
SELECT H.lvl + 1 AS lvl
,ES.emp
,ES.sup
FROM EmployeeSupervisor ES
INNER JOIN Hier H
ON ES.sup = H.emp
WHERE H.lvl + 1 <= 5 -- max of 5 levels
AND ES.sup != ''
)
SELECT *
FROM Hier
I have tried a few variations on PIVOT with COALESCE to get the desired output (shown by query below), with no success.
-- expected output
SELECT *
FROM (
VALUES ('mike','lisa','ken','scott','chris')
,('kevin','lisa','ken','scott','chris')
,('lisa','ken','scott','chris', NULL)
,('ken','scott','chris', NULL, NULL)
,('scott','chris', NULL, NULL, NULL)
,('chris',NULL, NULL, NULL, NULL)
) Expected(lvl1, lvl2,lvl3,lvl4,lvl5)
There are lots of similar questions out there, but none that truly addresses the nature of this one.
- Edit: Using SQL Server 2016, and hoping to avoid numerous, repeated joins in favor or recursive CTE.