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