Suppose you have a standard org hierarchy table in Oracle. For simplicity sake, assume that you have a column in that Org table that shows how many employees are DIRECTLY assigned to that org.
create table org (
org_id NUMBER(5),
parent_org_id NUMBER(5),
emp_count NUMBER (5)
);
insert into org values (1, NULL, 200);
insert into org values (2, 1, 50);
insert into org values (3, 1, 100);
insert into org values (4, 2, 100);
Is it possible to get a result set that looks like this:
OrgID, Count
1, 450
2, 150
3, 100
4, 100
That is, there are not 450 people DIRECTLY assigned to OrgId1, but when you add up everyone in OrgID1 and BELOW, there are 350 people directly or indirectly assigned. Again, with OrgId2, there are 50 assigned directly + the 100 assigned under it (in Org 4).
Simple idea right? Is this kind of query possible in Oracle?
This can be done with a hierarchical query the ‘wrong’ way round – no
start withclause means every row is a start point, then traverse the tree to each leaf and group up the results by each start point: