To add some color to what Visakh was suggesting, what I meant by using recursive CTE is something like what I am showing below. I am still using a static pivot - you can extend it even if you have a large number of levels, but if you have an unknown number of levels, you would need dynamic pivoting. Take a look at Madhivanan's blog for a dynamic pivot function.-- My simplified test table----------------------------------------------CREATE TABLE #tmp (cid INT , cname VARCHAR(32), pid INT, pname VARCHAR(32))INSERT INTO #tmp VALUES(1,'p1',NULL,NULL),(2,'p2',NULL,NULL),(3,'c1',1,'p1'),(4,'c2',2,'p2'),(5,'g1',3,'c1'),(6,'g2',4,'c2');-- Recursive query-------------------------------------------------------;WITH cte AS( SELECT *, ROW_NUMBER() OVER (ORDER BY cid) AS RN, 1 AS lvl FROM #tmp a WHERE NOT EXISTS (SELECT * FROM #tmp b WHERE a.cid = b.pid) UNION ALL SELECT t.*, c.RN, c.lvl+1 FROM #tmp t INNER JOIN cte c ON t.cid = c.pid),cte2 AS( SELECT cname, lvl, RN FROM cte)--- Static pivoting------SELECT *FROM cte2PIVOT( MAX(cname) FOR lvl IN ([1],[2],[3])) P;-- CLEANUP -------------------------------------------------------DROP TABLE #tmp;
BTW, it should/would work even if you have multiple children/grandchildren, and even if there are people with and without children at the same level - but I have not tested those.