Sql 查询以获取层次结构表中父级的所有级别的子级

Sql 查询以获取层次结构表中父级的所有级别的子级,sql,sql-server,Sql,Sql Server,我的表格结构如下 孩子气的 父ID 1. 3. 2. 3. 3. 4. 4. 无效的 你有一个奇怪的要求。除了遍历层次结构之外,您还希望所有节点都与其自身配对。这不是原始数据的一部分,但可以单独添加: with cte as ( select parentId, childid from t where parentid is not null union all select cte.parentId, t.childid

我的表格结构如下

孩子气的 父ID 1. 3. 2. 3. 3. 4. 4. 无效的
你有一个奇怪的要求。除了遍历层次结构之外,您还希望所有节点都与其自身配对。这不是原始数据的一部分,但可以单独添加:

with cte as (
      select parentId, childid
      from t
      where parentid is not null
      union all
      select cte.parentId, t.childid
      from cte join
           t
           on t.parentId = cte.childId
     )
select *
from cte
union all
select childid, childid
from t;

是一个dbfiddle。

不确定为什么要在层次结构之外添加额外的条目,但您可以这样做

declare @T table (
    id        integer identity(1,1) primary key,
    ChildId   Integer,
    ParentId  Integer
)

insert @T (ChildId, Parentid)
      select 4,null
union select 3,4
union select 2,3
union select 1,3

;WITH CTE (ParentId, ChildId, Lvl) AS (
    SELECT ParentId, ChildId, 1
      FROM @T 
     WHERE ParentId IS NULL
UNION ALL
    SELECT T.ParentId, T.ChildId, Lvl + 1
      FROM @T T JOIN CTE E ON E.ChildId = T.ParentId
)
SELECT ChildId,ParentId,Lvl
  FROM CTE
 ORDER BY Lvl

请避免粘贴屏幕快照,并显示您已经尝试过的层次结构列类型。这将允许您在不使用递归CTE的情况下执行所需的查询“我尝试使用递归CTE,但无法实现所需的输出”,这是什么尝试?如果您不包含上述代码,我们无法回答您的问题,即为什么您的代码不起作用。