从tsql中的行集数据(具有特定id)获取所有树

Ali*_*adi 6 t-sql tree recursive-query

我的数据在表中有2个字段,Id和ParentId.我用这种结构存储数据(下面的类似图像).如何获得包含Id = 6的从叶到根的所有路径?(结果样本如下)

--Data structure is as follow :
--  1
-- /
--2 <- 3       9
-- \    \    / 
--  4 <- 5  7  8
--    \  /  /  /
--      6 - - -
--   /    \
--  10  <- 11
-- /
--12

--Data In Table Is :
--Id    ParentId
--1     null
--2     1
--3     2
--4     2
--5     3
--5     4
--6     4
--6     5
--6     7
--6     8
--7     9
--8     null
--9     null
--10    6
--11    6
--11    10
--12    10

--Result for all trees that include "Id = 6":
--12 > 10 > 6 > 4 > 2 > 1
--12 > 10 > 6 > 5 > 4 > 2 > 1
--12 > 10 > 6 > 5 > 3 > 2 > 1
--12 > 10 > 6 > 7 > 9
--12 > 10 > 6 > 8
--11 > 10 > 6 > 4 > 2 > 1
--11 > 10 > 6 > 5 > 4 > 2 > 1
--11 > 10 > 6 > 5 > 3 > 2 > 1
--11 > 10 > 6 > 7 > 9
--11 > 10 > 6 > 8
--11 > 6 > 4 > 2 > 1
--11 > 6 > 5 > 4 > 2 > 1
--11 > 6 > 5 > 3 > 2 > 1
--11 > 6 > 7 > 9
--11 > 6 > 8
Run Code Online (Sandbox Code Playgroud)

小智 4

你的表说 4 将自身作为父级,但没有其他任何内容,但你有一行指出 12 > 10 > 6 > 5 > 4 > 2 > 1 所以我无法通过该设置产生相同的结果。

我的 sqlfiddle 在这里:http://sqlfiddle.com/#!6/873b9/3

假设 4 有 2 作为父级,我的代码如下所示(顺序可能有点不同,但它的 SQL 所以没关系):

WITH records as
(
  SELECT
  leaf.Id
  ,leaf.ParentId
  ,case when NOT EXISTS(SELECT * FROM recTest where ParentId = leaf.Id) then 1 else 0 end as isLeaf
  FROM recTest as leaf
)
,hierarchy as
(
  SELECT Id
  ,NULL as ParentId
  ,cast(Id as varchar(100)) as chain
  ,isLeaf
  FROM records
  where ParentId IS NULL
  UNION ALL
  SELECT r.Id
  ,r.ParentId
  ,cast(cast(r.Id as varchar(100)) + ' > ' + h.chain as varchar(100)) as chain
  ,r.isLeaf
  FROM records as r
    INNER JOIN hierarchy as h
      ON r.ParentId = h.Id
)
SELECT
h.chain
FROM hierarchy as h
WHERE isLeaf = 1
AND h.chain like '%6%'
OPTION (MAXRECURSION 0)
Run Code Online (Sandbox Code Playgroud)