【问题标题】:every parent in the tree for each child with level for grand parent as 1每个孩子的树中的每个父母,祖父母的级别为 1
【发布时间】:2015-08-10 17:05:42
【问题描述】:

假设我们有以下数据集。

PARENT     CHILD
---------- -----------
S1         S2
S2         S3
S3         S4
S4         S5
S5

我想为每个孩子列出树中的每个父母。 例如,

CHILD      PARENT        LEVEL
---------- -----------  ------
S5         S4              4
S5         S3              3
S5         S2              2
S5         S1              1
S4         S3              3
S4         S2              2
S4         S1              1
etc......

【问题讨论】:

    标签: sql plsql


    【解决方案1】:
    with 
        tbl as (select 'S1' as parent,'S2'  as child from dual union all
                        select 'S2' as parent,'S3'  as child from dual union all
                        select 'S3' as parent,'S4'  as child from dual union all
                        select 'S4' as parent,'S5'  as child from dual union all
                        select 'S5' as parent, null as child from dual)
        ,tree as (select connect_by_root(t.child) r
                                        ,t.child,t.parent
                                        ,level l from tbl t
                            where child is not null
                            connect by  prior parent =child)
    select r as "CHILD"
                ,parent  as "PARENT"
                ,max(l) over (partition by r) - l + 1 as "LEVEL"
    from tree
    where r is not null
    order by r desc, l
    

    SQL Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 2011-12-19
      • 2023-03-23
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多