2013-11-29 69 views
0

我有這樣的表結構,它就像樹結構,如何找出人的數量是在特定的referreid下,被觸發的id是什麼,但clientId,我嘗試了幾個方法,但它會嵌套循環...查找在樹狀結構中使用sql查詢的人數

 
    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

問題不清楚客戶端id引用id是相同的,所以y兩個字段? – Bunny

+0

這就像二叉樹結構,假設Reffere Id 2是節點,它有兩個孩子,如1,3。而1和3作爲Node,它有兩個孩子,分別是4,5和6,7等......,它繼續像嵌套循環@兔子,@ ViSu –

回答

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 |