在层次结构表中获取最终父级

时间:2016-07-05 23:36:17

标签: sql sql-server hierarchical-data recursive-query

我有一个包含父/子信息的SQL表,如

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

我的结果应该是

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

每一行都应该有子级及其最后一个父级。

如何在SQL Server中执行此操作?

1 个答案:

答案 0 :(得分:0)

是的,可以使用递归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