我有这样的表结构,它就像树结构,如何找出人的数量是特定的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
答案 0 :(得分:0)
您可以使用递归CTE。
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 |