自嵌套SQL连接

时间:2018-12-11 09:31:59

标签: sql sql-server join nested relation

此表需要此结果。 这是3列,我想要3个带有嵌套节点的结果。 真的,我希望每个节点都具有self和parent这样的结果

ID/ Number/SelfRef
21092   100 NULL
21093   50  NULL
21094   30  21093
21095   20  21093
21096   -30 21093
21097   5   21095
21098   15  21095
21099   -5  21095

我需要这个结果

21097    5     21097
21097    5     21095 
21097    5     21093

这是我的逻辑

this is my logic

1 个答案:

答案 0 :(得分:0)

这对我有用

;WITH
    cte1 AS
    (   -- Recursively build the relationship tree
        SELECT      SelfRef
                ,   ID
                ,   AscendentLevel = 1
        FROM        [Kharid].[IdentityGharardadKalaTedad]
        UNION ALL
        SELECT      t.SelfRef
                ,   cte1.ID
                ,   AscendentLevel = cte1.AscendentLevel + 1
        FROM        cte1
        INNER JOIN  [Kharid].[IdentityGharardadKalaTedad]    t   ON t.ID = cte1.SelfRef
    ),
    cte2 AS
    (   -- Now find the ultimate parent
        SELECT      SelfRef
                ,   ID
                ,   rn = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AscendentLevel DESC)
        FROM        cte1
    )

SELECT  *
FROM    cte2
Order by id