假设您有一个这样的表(SQL SERVER 2005)
pairID childID parentID
0 1 2
1 2 3
2 3 4
你有一个返回这个数据集的 CTE:
pairID childID parentID level
0 1 2 2
1 2 3 1
2 3 4 0
如何保存初始子 ID,以便获得此结果集:
pairID childID parentID level
0 1 2 2
1 1 3 1
2 1 4 0
所以基本上我正在做的是保留原来的孩子ID并返回它而不是另一个......
这是迄今为止的 CTE 查询,效果很好:
WITH TESTER AS (SELECT a.PairID,
a.ChildID,
a.ParentID,
0 AS Level
FROM
BusinessHierarchy AS a
LEFT OUTER JOIN BusinessHierarchy AS a2
ON a.ParentID = a2.ChildID
WHERE (a2.PairID IS NULL)
UNION ALL
SELECT b.PairID, b.ChildID, b.ParentID, oh.Level + 1 AS Level
FROM BusinessHierarchy AS b INNER JOIN
TESTER AS oh ON b.ParentID = oh.ChildID)
SELECT PairID, ChildID, ParentID, Level
FROM TESTER AS x
ORDER BY Level, ChildID, ParentID