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