Created
September 18, 2013 13:19
-
-
Save bitsprint/6609041 to your computer and use it in GitHub Desktop.
Maintain the top parent record in a hierarchy. Here we specify the hierarchy level in the query as we traverse the hierarchy. Ultimately we can select only the records at the highest level giving us the top parent record at every step in the hierarchy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CREATE TABLE #Test (CompanyID INT, CompanyName VARCHAR(20), LinkedCompanyID INT) | |
| INSERT INTO #Test | |
| SELECT 1, 'Company A', NULL UNION | |
| SELECT 2, 'Company B', 1 UNION | |
| SELECT 3, 'Company C', 2 UNION | |
| SELECT 4, 'Company D', 2 UNION | |
| SELECT 5, 'Company E', 4 UNION | |
| SELECT 6, 'Company F', 3 UNION | |
| SELECT 7, 'Company G', NULL | |
| ;WITH CTE AS | |
| ( SELECT *, 0 [Level] | |
| FROM #Test | |
| UNION ALL | |
| SELECT CTE.CompanyID, CTE.CompanyName, #Test.LinkedCompanyID, Level + 1 | |
| FROM CTE | |
| INNER JOIN #Test | |
| ON CTE.LinkedCompanyID = #Test.CompanyID | |
| WHERE #Test.LinkedCompanyID IS NOT NULL | |
| ) | |
| SELECT c.CompanyID, c.CompanyName, c.LinkedCompanyID | |
| FROM ( SELECT *, MAX([Level]) OVER (PARTITION BY CompanyName) [MaxLevel] | |
| FROM CTE | |
| ) c | |
| WHERE MaxLevel = Level | |
| DROP TABLE #Test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment