如何通过在sql server中使用5个parentids跳转来获取子ID

时间:2016-10-13 09:12:17

标签: sql sql-server

我有很多记录。根节点的父ID为空,如果我开始遍历父ID,则从叶节点开始,我将在6-10次跳转后到达根节点。所以我知道当前节点(叶子或中间节点)的ID。有没有办法有效地找到那个孩子的深度?

1 个答案:

答案 0 :(得分:1)

在这里,我只是通过父母 - 子女关系来平衡每一行(递归CTE),就像最高父母是1级,他们的第一个孩子是2级,然后是3,4继续。现在你可以从那里寻找具有条件Parent和Level的任何行。

;WITH INITIAL AS
(

    SELECT * FROM          --You will change this dummy data by your table.
    (VALUES                --You will change this dummy data by your table.
        ('P1', NULL),      --You will change this dummy data by your table.
        ('C1', 'P1'),      --You will change this dummy data by your table.
        ('C2', 'P1'),      --You will change this dummy data by your table.
        ('C11', 'C1'),     --You will change this dummy data by your table.
        ('P2', NULL)       --You will change this dummy data by your table.
    ) TC(ID, ParentID)     --You will change this dummy data by your table.

), FINAL AS 
(
    -- Anchor
    SELECT ID,
    ParentID,
    LEVEL = 1
    FROM   INITIAL

    UNION ALL

    -- Recursion
    SELECT D.ID,
    D.ParentID,
    LEVEL = LEVEL + 1
    FROM INITIAL D
    INNER JOIN FINAL RC
    ON RC.ID = D.ParentID
), MyLastTable AS
(
    SELECT 
    TOP 1 WITH TIES 
    * 
    FROM FINAL
    ORDER  BY Row_number()OVER(PARTITION BY ID ORDER BY LEVEL DESC) 
) SELECT * FROM MyLastTable 
WHERE LEVEL = 2 AND ParentID = 'P1' -- Change here with your condition

根据您自己的数据和MyTable更改INITIAL表值,其中查询的最后条件为您的要求。