Here was the initial problem:
CREATE TABLE #Organizations (ID INT, Number INT, Name varchar(30), SuperiorOrganizationID INT) INSERT INTO #Organizations VALUES (1, 1, 'Dell', NULL), (2, 2, 'HP', NULL), (3, 100, 'IBM World', NULL), (4, 150, 'IBM Europe', 3), (5, 159, 'IBM Germany', 4) Select Number, Name, TopMostOrganizationID = 'TO SOLVE' From #Organizations DROP TABLE #Organizations
Here is the initial solution (thanks to Sarat):
;with cte(ID,Number, Name, SuperiorOrganizationID,TopMostOrganizationID) AS ( Select ID,Number, Name, SuperiorOrganizationID,ID as TopMostOrganizationID From #Organizations where SuperiorOrganizationID is null UNION ALL Select A.ID,A.Number, A.Name, A.SuperiorOrganizationID,B.TopMostOrganizationID as TopMostOrganizationID From #Organizations A INNER JOIN cte B ON A.SuperiorOrganizationID= B.ID ) select A.Number, A.Name, A.TopMostOrganizationID from cte A
Now the only think I need to solve is to have a column in cte table that will show count of levels. In the given example, the result should be:
Number, Name, TopMostOrganizationID, SuperiorOrganizationsCount
1, 'Dell', 1, 0 2, 'HP', 2, 0 100, 'IBM World', 3, 0 150, 'IBM Europe', 3, 1 159, 'IBM Germany', 3, 2