I found this to be an interesting problem so I spent some time on it (Peso would probably have done it in milliseconds, I spent a bit more
). Please note that if you have several rows on the last leaf only one of them will be returned, if you want all nodes in the last leaf change the ROW_NUMBER() to RANK().DECLARE @table table ( DetailsID int, FollowupID int )INSERT INTO @tableSELECT 1, 0 UNION ALL SELECT 2, 0 UNION ALLSELECT 3, 1 UNION ALL SELECT 4, 2 UNION ALLSELECT 5, 3;SELECT * FROM @table;WITH cte (DetailsID, FollowupID, Level, Path) AS ( SELECT DetailsID, FollowupID, Level = 0, Path = CAST(DetailsID AS varchar(max)) FROM @table WHERE FollowupID = 0 UNION ALL SELECT a.DetailsID, a.FollowupID, Level = b.Level + 1, Path = Path + '/' + CAST(a.DetailsID AS varchar(max)) FROM @table a INNER JOIN cte b ON a.FollowupID = b.DetailsID )SELECT DetailsID, FollowupID, Level, Path FROM cte WHERE Level = 0UNIONSELECT DetailsID, FollowupID, Level, Path FROM ( SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY LEFT(Path, PATINDEX('%/%', Path)-1) ORDER BY Level DESC) FROM cte WHERE Level > 0 ) AS aWHERE RowNum = 1ORDER BY Path
- LumbagoMy blog (yes, I have a blog now! just not that much content yet) -> www.thefirstsql.com