自嵌套SQL连接

问题描述 投票:-3回答:1

我需要这个结果这个表。这是3列,我希望嵌套节点有3个结果。我真的希望每个节点都有自己和父类似的结果

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

这是我的逻辑

sql sql-server join nested relation
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.