How to obtain total children count for all parents in Oracle tree hierarchy?

南楼画角 提交于 2019-12-08 13:13:03

问题


I have an Oracle Tree hierarchy structure that is basically similar to the following table called MY_TABLE

(LINK_ID,
 PARENT_LINK_ID,
 STEP_ID )

with the following sample data within MY_TABLE:

LINK_ID     PARENT_LINK_ID      STEP_ID
-----------------------------------------------
A           NULL                0
B           NULL                0
AA          A                   1
AB          A                   1
AAA         AA                  2
BB          B                   1
BBB         BB                  2
BBBA        BBB                 3
BBBB        BBB                 3

Based on the above sample data, I need to produce a report that basically returns the total count of rows for all children of both parent link IDs (top level only required), that is, I need to produce a SQL query that returns the following information, i.e.:

PARENT  RESULT COUNT
----------------------------
A       3
B       4   

So I need to rollup total children that belong to all (parent) link ids, where the LINK_IDs have a PARENT_LINK_ID of NULL


回答1:


I think something like this:

select link, count(*)-1 as "RESULT COUNT"
  from (
    select connect_by_root(link_id) link
    from my_table
    connect by nocycle parent_link_id = prior link_id
    start with parent_link_id is null)
group by link
order by 1 asc



回答2:


Please try:

WITH parent(LINK_ID1, LINK_ID, asCount) AS
(
  SELECT LINK_ID LINK_ID1, LINK_ID, 1 as asCount  
  from MY_TABLE WHERE PARENT_LINK_ID is null

  UNION ALL 

  SELECT LINK_ID1, t.LINK_ID, asCount+1 as asCount  FROM parent
  INNER JOIN MY_TABLE t ON t.PARENT_LINK_ID =  parent.LINK_ID
    )
select 
  LINK_ID1 "Parent", 
  count(asCount)-1 "Result Count"
From parent 
group by LINK_ID1;

SQL Fiddle Demo



来源:https://stackoverflow.com/questions/19900665/how-to-obtain-total-children-count-for-all-parents-in-oracle-tree-hierarchy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!