0

我们有一个像这样用树形结构的表格:伯爵的后代行

Id Desc ParentID 
=== 
A DescrA NULL 
B DescrB A 
C DescrC A 
D DescrD C 
E DescrE C 
F DescrF E 

我们需要返回的后代的数量(包括subdescendants)的特定ID的,类似的查询:

select count(descendants) from Tablex where id='A' --result = 5 
select count(descendants) from Tablex where id='B' --result = 0 
select count(descendants) from Tablex where id='C' --result = 3 
select count(descendants) from Tablex where id='E' --result = 1 

我们已经看到它会作出“易”与CTE但不可能得到它的要点...

回答

2
declare @T table 
(
    Id char(1), 
    ParentId char(1) 
); 

insert into @T values 
('A', NULL), 
('B', 'A'), 
('C', 'A'), 
('D', 'C'), 
('E', 'C'), 
('F', 'E'); 

declare @ParentId char(1); 
set @ParentId = 'A'; 

with C as 
(
    select Id, ParentId 
    from @T 
    where ParentId = @ParentId 
    union all 
    select T.Id, T.ParentId 
    from @T as T 
    inner join C 
     on T.ParentId = C.Id 
) 
select count(*) 
from C; 
+0

完美,谢谢! – VSP