2010-05-12 48 views
2

如果我有一個母親爲&父親的家庭的公用表表達式,我該如何增加'Generation'計數器?一個家庭應該讓孩子一代爲零,父母爲一代,父母代爲二代。但循環執行兩次,每組祖父母一次。帶有2個聯合的公用表表達式計數器

;WITH FamilyTree 
AS 
(
    SELECT *, 0 AS Generation 
    FROM myTable 
    WHERE [id] = 99 

    UNION ALL 
    SELECT name, Generation + 1 
    FROM myTable AS Fam 
    INNER JOIN FamilyTree 
    ON Fam.[id] = FamilyTree.[motherid] 

    UNION ALL 
    SELECT name, Generation + 1 
    FROM myTable AS Fam 
    INNER JOIN FamilyTree 
    ON Fam.[id] = FamilyTree.[fatherid] 
) 
SELECT generation, name FROM FamilyTree 

回答

4

一次性改變連接查看一代親代中的親戚,而不是在CTE中有2個遞歸子句。這兩個子句形成了一個部分交叉連接,這就是爲什麼你有多餘的行

;WITH FamilyTree 
AS 
(
    SELECT *, 0 AS Generation 
    FROM myTable 
    WHERE [id] = 99 

    UNION ALL 
    SELECT name, Generation + 1 
    FROM myTable AS Fam 
    INNER JOIN FamilyTree 
    ON Fam.[id] IN (FamilyTree.[motherid], FamilyTree.[fatherid]) 
) 
SELECT generation, name FROM FamilyTree 
+0

完美,謝謝。 – simon831 2010-05-12 11:49:35