Hello everyone,
I was wondering if anyone could help and guide me to achieve intermediate counts on a recursive query.
I have a structure like this:
CREATE TABLE grp (id number, pid number, name varchar2(10));
insert into grp values(1, null, 'grp1');
insert into grp values(11, 1, 'grp11');
insert into grp values(12, 11, 'grp12');
insert into grp values(13, 12, 'grp13');
insert into grp values(14, 12, 'grp14');
insert into grp values(2, null, 'grp2');
commit;
WITH t(id, pid, lvl, ident) AS
(
SELECT id, pid, 1, name FROM grp WHERE pid IS NULL
UNION ALL
SELECT c.id, c.pid, t.lvl +1, lpad(' ', t.lvl) || c.name FROM grp c, t WHERE t.id = c.pid
)
SEARCH DEPTH FIRST BY id SET rnk
select id, pid, lvl, ident from t;
ID PID LVL IDENT
---------- ---------- ---------- ----------
1 1 grp1
11 1 2 grp11
12 11 3 grp12
13 12 4 grp13
14 12 4 grp14
2 1 grp2
6 rows selected.
I was wondering if there is any easy way to create intermediate counts? To have something like:
ID PID LVL IDENT direct total
---------- ---------- ---------- ---------- ------ -------
1 1 grp1 1 4
11 1 2 grp11 1 3
12 11 3 grp12 2 2
13 12 4 grp13 0 0
14 12 4 grp14 0 0
2 1 grp2 0 0
For each level, I would like to have 2 columns. One that will count only immediate children. And, the other one that should count ALL descending nodes from the current level. I could probably do this using a function that will select and count. But, I was wondering if there is a way in pure SQL?
Any suggestion is welcome,
Regards,