在SQL Server中执行递归自联接的最简单的方法?

在SQL Server中执行递归自联接的最简单的方法是什么?我有一个这样的表:

PersonID | Initials | ParentID
1          CJ         NULL
2          EB         1
3          MB         1
4          SW         2
5          YT         NULL
6          IS         5

我想要能够获得只与特定人开始的层次结构相关的记录。所以如果我请求CJ的层次结构PersonID = 1我会得到:

PersonID | Initials | ParentID
1          CJ         NULL
2          EB         1
3          MB         1
4          SW         2

对于EB,我会得到:

PersonID | Initials | ParentID
2          EB         1
4          SW         2

我有点卡在这可以不能想到如何做它从基于一连串的固定深度响应。这将会发生,因为我们不会有很多级别,但我想要做到正确。

谢谢!
克里斯。

WITH    q AS 
        (
        SELECT  *
        FROM    mytable
        WHERE   ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q

通过添加排序条件,可以保留树顺序:

WITH    q AS 
        (
        SELECT  m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    mytable m
        WHERE   ParentID IS NULL
        UNION ALL
        SELECT  m.*,  q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q
ORDER BY
        bc

通过更改ORDER BY条件,您可以更改兄弟姐妹的顺序。

http://stackoverflow.com/questions/1757260/simplest-way-to-do-a-recursive-self-join-in-sql-server

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:在SQL Server中执行递归自联接的最简单的方法?