Please post test data in a comsumable format:CREATE TABLE #temp( article varchar(20) NOT NULL ,part varchar(20) NOT NULL);INSERT INTO #tempVALUES ('article1', 'article1a') ,('article1', 'article1b') ,('article2', 'article1a') ,('article2', 'article2b') ,('article2b', 'article3a') ,('article2b', 'article3b');
I fail to see how you can get your results from the test data.Try playing with something like:WITH PartsAS( SELECT DISTINCT CAST(NULL AS varchar(20)) AS parent ,article ,1 AS hlevel FROM #temp A WHERE NOT EXISTS ( SELECT 1 FROM #temp A1 WHERE A1.part = A.article ) UNION ALL SELECT A.article, A.part, P.hlevel + 1 FROM #temp A JOIN Parts P ON A.article = P.article),PartNosAS( SELECT ROW_NUMBER() OVER (ORDER BY hlevel, parent, article) AS RN ,parent, article FROM Parts WHERE parent IS NOT NULL)SELECT P.RN, P1.RN AS ParentRN ,P.parent as article ,P.article as partFROM PartNos P LEFT JOIN PartNos P1 ON P.parent = P1.articleORDER BY RN;