0

Right now I have a dataset like this; (8 records)

cid    pid 
108    100 
108    100 
423    400 
423    400 
100    0   
100    0   
100    0   
200    0   

the tree like as follows:

root -- 0
--child 100
  --sub child 108
     ---sub ...(maybe has more level)
--child 200
  --sub child 205
--child 400
  --sub child 423

And I want to count all sum records each by ever child (not sub child, sub child's record should calculate into it's father or grandfather until the first level child node).

so the result should like:

node    counts
100       5
200       1
400       2

But when I use start with connect by and with group by keywords I cannot get the expected result.

my sql is as follows:

select cid as node,count(1) as counts 
from (one subselect for get the 8 records) a 
start with a.pid = '0' 
connect by prior a.cid = a.pid) t group by cid;

result is empty.. who can help me? or who knows the detail for the oracle group by keywords works when used together with a tree structure?

alardear
  • 3
  • 5

1 Answers1

0

Try this:

SELECT top_cid, Count(1) FROM (
  WITH
    parent_child as (
      select distinct a.cid, a.pid from a
      union  
      select a.pid, 0 from a
      where a.pid<>0 and not exists (
        select 1 from a a1 where a1.cid=a.pid
      )
    ),
    tree as (
      select level as lvl,
        --connect_by_root in 10g and above
        replace(sys_connect_by_path(decode(level, 1, cid), '~'), '~') AS top_cid, 
        pid, cid 
      from parent_child
      start with pid = 0
      connect by prior cid = pid(+)
    )
  select tree.top_cid, a.pid, a.cid 
  from a, tree
  WHERE a.cid=tree.cid
) GROUP BY top_cid
some1
  • 857
  • 5
  • 11