2

如果我有一个有母亲和父亲的家庭的公用表表达式,我该如何增加“世代”计数器?一个家庭应该将孩子作为第 0 代,将父母作为第 1 代,将四个祖父母作为第 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

1 回答 1

4

一口气改个代沟看亲戚的join,而不是CTE里有2个递归子句。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 
于 2010-05-12T11:06:31.227 回答