您可以使用遞歸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 |
問題不清楚客戶端id引用id是相同的,所以y兩個字段? – Bunny
這就像二叉樹結構,假設Reffere Id 2是節點,它有兩個孩子,如1,3。而1和3作爲Node,它有兩個孩子,分別是4,5和6,7等......,它繼續像嵌套循環@兔子,@ ViSu –