如何计算Oracle树层次结构中所有父代的子代总数?

jtoj6r0c  于 2023-06-22  发布在  Oracle
关注(0)|答案(1)|浏览(122)

我有一个类似于下表Hierarchy_Tree的Oracle树层次结构

(PARENT,  CHILD)

使用Hierarchy_Tree中的以下示例数据:

CHILD   PARENT  
-------------------------
AA          A                   
AB          A                   
AAA         AA                  
BB          B                   
BBB         BB                  
BBBA        BBB                 
BBBB        BBB  
C1           C
C2           C
C3           C
C4           C3
C5           C3
C6           C3
C7           C6
C8           C6

基于上面的示例all parent(仅需要顶层),也就是说,我需要生成一个返回以下信息的SQL查询,即:

PARENT   COUNT
----------------------------
A       3
B       4  
C       8

因此,我需要汇总属于所有PARENT的所有子项
我试过类似的东西,但它没有工作。

select child1, count(*)-1 as "RESULT COUNT"
  from (
    select connect_by_root(child) child1
    from Hierarchy_Tree
    connect by nocycle parent = prior child
    )
group by child1
order by 1 asc
ivqmmu1c

ivqmmu1c1#

select rootp as parent, count(*) as count from (
    select child, parent, connect_by_root parent as rootp from Hierarchy_Tree
    start with parent in (select parent from Hierarchy_Tree d1
    where not exists(select 1 from Hierarchy_Tree d2 where d2.child = d1.parent)
    )
    connect by parent = prior child
)
group by rootp
;

A   3
B   4
C   8

相关问题