计算表树中的后代行

时间:2012-06-14 08:03:03

标签: sql-server sql-server-2008 tsql tree common-table-expression

我们有一个像这样的树结构的表:

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

我们需要一个返回特定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“轻松”制作,但无法得到它的要点......

1 个答案:

答案 0 :(得分: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;