2

我有一个具有递归层次结构的表(即 ID、ParentID)。对于此层次结构中的任何项目,我希望能够带回层次结构上下所有内容的列表以及每一行的级别。假设父母只能有一个孩子。

举个例子:

ID    ParentID
--------------
1     NULL
2     1
3     2
4     NULL
5     4
6     5

给定 ID 1、2 或 3,我想返回:

ID    ParentID    Level
-----------------------
1     NULL        1
2     1           2
3     2           3

我以前做过,但我不记得是怎么做的。我知道解决方案涉及 CTE,但我无法正确解决!任何帮助表示赞赏。

4

3 回答 3

5
;with cte as 
(
    select *, 1 as level from @t where id = @yourid
    union all
    select t.*, level - 1
    from cte 
        inner join @t t on cte.parent = t.id
),
cte2 as
(   
    select * from cte
    union all
    select t.*, level+1
    from cte2 
        inner join @t t on cte2.id = t.parent

)
    select id,parent, ROW_NUMBER() over (order by level) level
    from (  select distinct id, parent, level from cte2) v
于 2012-09-28T14:34:47.617 回答
0

我能想到的最简单的 CTE 查询版本是:

WITH Ancestry (AncestorID, DescendantID)
AS
(
    SELECT 
        ParentID, ID
    FROM
        dbo.Location
    WHERE
        ParentID IS NOT NULL
UNION ALL
    SELECT 
        P.AncestorID, C.ID
    FROM
        dbo.Location C
    JOIN
        Ancestry P on C.ParentID = P.DescendantID
)
SELECT * FROM Ancestry

结果是表中存在的所有祖先/后代关系的列表。

最后的“SELECT * FROM Ancestry”可以用更复杂的过滤、排序等替换。

To include reflexive relationships, the query can be modified by adding two lines to the final SELECT statement:

SELECT * FROM Ancestry
UNION
SELECT ID, ID FROM dbo.Location
于 2015-05-12T15:57:57.000 回答
-1
;WITH Recursive_CTE AS (
     SELECT
          child.ExecutiveId,
          CAST(child.ExecutiveName as varchar(100)) BusinessUnit,
          CAST(NULL as bigint) ParentUnitID,
          CAST(NULL as varchar(100)) ParentUnit,
          CAST('' as varchar(100)) LVL,
          CAST(child.ExecutiveId as varchar(100)) Hierarchy,
      1 AS RecursionLevel
     FROM Sales_Executive_level child
     WHERE ExecutiveId = 4000 --your Id which you want to get all parent node
     UNION ALL 
     SELECT
      child.ExecutiveId,
      CAST(LVL + child.ExecutiveName as varchar(100)) AS BusinessUnit,
      child.ParentExecutiveID,
      parent.BusinessUnit ParentUnit,
      CAST('' + LVL as varchar(100)) AS LVL,
      CAST(Hierarchy + ':' + CAST(child.ExecutiveId as varchar(100)) as varchar(100)) Hierarchy,
      RecursionLevel + 1 AS RecursionLevel
     FROM Recursive_CTE parent 
     INNER JOIN Sales_Executive_level child ON child.ParentExecutiveID = parent.ExecutiveId                           
    )
    SELECT * FROM Recursive_CTE ORDER BY Hierarchy  
    OPTION (MAXRECURSION 300); 
于 2014-05-01T09:56:31.170 回答