Search code examples
sqltreeoracle11g

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


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


Solution

  • 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