2016-07-05 55 views
0

我有父母和孩子信息的SQL表像获取层次结构表最终母公司

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

我的结果应该是像

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

每一行中应该有孩子,其最终母公司及其层次结构。

我怎么能在SQL Server中做到这一点?

+0

'这是哪种RDBMS?请添加一个标签来指定您是使用'mysql','postgresql','sql-server','oracle'还是'db2' - 或者其他的东西。 –

+0

如果您使用支持[现代SQL](http://modern-sql.com/slides)的DBMS,则可以使用递归公用表表达式。查看标有[tag:recursive-query]的解决方案 –

+0

我正在使用sql server –

回答

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 
+0

非常感谢 –