Count of superior organizations in Recursive

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

July 18th, 2013 4:49am

Try this

;with cte(ID,Number, Name, SuperiorOrganizationID,TopMostOrganizationID,CompLevel)
AS 
(
Select ID,Number, Name, SuperiorOrganizationID,ID as TopMostOrganizationID  ,0 CompLevel  From #Organizations where SuperiorOrganizationID is null 
UNION ALL
Select A.ID,A.Number, A.Name, A.SuperiorOrganizationID,B.TopMostOrganizationID,B.CompLevel+1    From #Organizations A 
INNER JOIN cte B
ON A.SuperiorOrganizationID= B.ID
)
select A.Number, A.Name, A.TopMostOrganizationID , a.CompLevel from cte A

Free Windows Admin Tool Kit Click here and download it now
July 18th, 2013 5:12am

yes it works... but I have another question regarding this example...

Lets say there is another column in table #Organizations. Its name is IsActive and it is of boolean type. Now I need to know the TopMostOrganizationID to return ID of that company that is the top most having Active column Yes (1).

July 18th, 2013 6:05am

Can i know the SQL version you use?
Free Windows Admin Tool Kit Click here and download it now
July 18th, 2013 6:19am

2008 r2
July 18th, 2013 6:23am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics