I had already had this coded when I I saw Lamprey's solution. It is similar but not exactly the same so I'll post it anyway
This can be done with a recursive CTE (common table expression)declare @t table (AssemblyKey int, AssemblyName varchar(20), ParentKey int)insert @tselect 0, 'System', NULLunion all select 1, 'System', NULLunion all select 2, 'SubAssembly', 0union all select 3, 'SubSubAssembly', 2union all select 4, 'SubAssembly', 1union all select 5, 'SubAssembly', 0;with cte (sysKey, AssemblyKey, descendant)as ( select AssemblyKey ,AssemblyKey ,0 from @t where ParentKey is null union all select c.sysKey ,t.AssemblyKey ,1 from cte c join @t t on t.ParentKey = c.AssemblyKey )select sysKey ,sum(descendant) descendantCountfrom ctegroup by sysKeyOUTPUTsysKey descendantCount----------- ---------------0 31 1
Be One with the OptimizerTG