获取层次结构中的最终父级 table

Getting final parent in hierarchy table

我有一个 SQL table,其中包含父子信息,例如

child  parent 
---------------
  a      b  
  b      c
  c      d
  e      f

我的结果应该是

child  parent
---------------
  a      d  
  b      d
  c      d
  e      f 

每一行在其层次结构中都应有子项及其最终父项。

如何在 SQL 服务器中执行此操作?

是的,可以使用递归 CTE。这是一个示例。

declare @tbl table(child varchar(5),  parent varchar(5))
insert @tbl values
  ('a',      'b'),  
  ('b',      'c'),
  ('c',      'd'),
  ('e',      'f')

  ;with tbl as (
  --anchor query
  --find starting level
  select parent child, parent parent, 0 lvl
  from @tbl t
  where parent not in (select child from @tbl)
  union all
  --recursive query
  select t.child, tbl.parent, lvl+1 --keep top level parent
  from @tbl t
  inner join tbl on t.parent=tbl.child --go up the tree to previous level
  )
  --filter final results
  select child,parent from tbl
  where lvl>0 --lvl 0 is fake level
  order by child