I am having a heck of a time with this. I am trying to write a query (using Oracle), against a table with a recursive relationship (hierarchical) and get the total number of re
This one is pretty straightforward:
09:38:54 HR@vm_xe> l
1 select sys_connect_by_path(dp.dir_name, '/') path
2 ,(select count(file_id)
3 from dirs dc
4 ,files f
5 where f.dir_id(+) = dc.dir_id
6 connect by prior dc.dir_id = dc.parent_dir_id
7 start with dc.dir_id = dp.dir_id
8 ) count
9 from dirs dp
10 connect by prior dp.dir_id = dp.parent_dir_id
11* start with dp.parent_dir_id is null
09:38:55 HR@vm_xe> /
PATH COUNT
------------------------------ ----------
/ROOT 6
/ROOT/DIR1_1 4
/ROOT/DIR1_1/DIR2_1 1
/ROOT/DIR1_1/DIR2_2 3
/ROOT/DIR1_2 2
5 rows selected.
Elapsed: 00:00:00.02
select sys_connect_by_path(D.dir_name, '/'), S.count_distinct_file_id
from DIRS D
inner join (select subtree_root_dir_id
, count(distinct file_id) count_distinct_file_id
from (select distinct connect_by_root D.DIR_ID subtree_root_dir_id
, F.file_id
from DIRS D
left outer join FILES F on F.dir_id = D.dir_id
start with 1=1 connect by prior D.dir_id = D.parent_dir_id)
group by subtree_root_dir_id) S
on D.dir_id = S.subtree_root_dir_id
start with D.dir_id = 1 connect by prior D.dir_id = D.parent_dir_id
Gives the results you asked for, but my gut says I am not seeing something, and that the query can be much simpler. (Please do not accept this answer until a few days have passed, in hopes that some one submits a better answer.)