查找在树结构中使用sql查询的人数

时间:2013-11-29 06:22:44

标签: sql-server-2008 c#-4.0 stored-procedures

我有这样的表结构,它就像树结构,如何找出人的数量是特定的referreid,Reffered id只是clientId,我尝试了几种方法,但它是嵌套循环... < / p>

     Id    ClientId ReferreId
     1  1   2
     2  3   2
     3  4   1
     4  5   1
     5  6   3
     6  7   3
     7  8   4
     8  9   4
     9  10  5
     10 11  5
     11 12  6
     12 13  6
     13 14  7
     14 15  7

1 个答案:

答案 0 :(得分:0)

您可以使用递归CTE。

SQL Fiddle

MS SQL Server 2008架构设置

create table YourTable
(
  Id int,
  ClientId int,
  ReferreId int
);

insert into YourTable values
(1  ,1   ,2),
(2  ,3   ,2),
(3  ,4   ,1),
(4  ,5   ,1),
(5  ,6   ,3),
(6  ,7   ,3),
(7  ,8   ,4),
(8  ,9   ,4),
(9  ,10  ,5),
(10 ,11  ,5),
(11 ,12  ,6),
(12 ,13  ,6),
(13 ,14  ,7),
(14 ,15  ,7);

查询1

declare @ReferreId int;
set @ReferreId = 2;

with C as
(
  select T.Id,
         T.ClientId,
         T.ReferreId
  from YourTable as T
  where T.ReferreId = @ReferreId
  union all
  select T.Id,
         T.ClientId,
         T.ReferreId
  from YourTable as T
    inner join C
      on T.ReferreId = C.ClientId
)
select count(*) as ChildCount
from C

<强> Results

| CHILDCOUNT |
|------------|
|         14 |