DeepDiverMom
Programmer
I need some advice for using an enhanced "CONNECT BY...START WITH" statement. (I know that Oracle MVP, "Sem" posted an excellent solution many months ago, but Tek-Tips's SEARCH feature is woefully inadequate to find his solution...I've unsuccessfully searched by every key word I can think of.) So, I'm hoping that Sem (or someone else) can help me.
Here is the table from which I'm working:
For anyone interested in helping, here are the "CREATE TABLE..." and "INSERTs" for the above data:
Here is a sample set of SQL-query code that gets me part-way to my solution:
But here is the output that I need, resulting from a roll-up of child...grandchild...great-grandchild data:
Thanks in advance for any help you can provide.
Here is the table from which I'm working:
Code:
select * FROM org;
ID NAME BUDGET PARENT_ID
---------- ---------- ---------- ----------
1 Company A
2 Region 1 1
3 Area 1 2
4 Office 1 3
5 Dept 1 100000 4
6 Dept 2 110000 5
7 Dept 3 105000 6
8 Office 2 3
9 Dept 1 112000 8
10 Dept 2 106000 8
11 Area 2 2
12 Office 1 11
13 Dept 1 140000 12
13 rows selected.
Code:
Create table org (id number, name varchar2(10),budget number, parent_id number);
Insert into org values (1,'Company A',null,null);
Insert into org values (2,'Region 1',null,1);
Insert into org values (3,'Area 1',null,2);
Insert into org values (4,'Office 1',null,3);
Insert into org values (5,'Dept 1',100000,4);
Insert into org values (6,'Dept 2',110000,4);
Insert into org values (7,'Dept 3',105000,4);
Insert into org values (8,'Office 2',null,3);
Insert into org values (9,'Dept 1',112000,8);
Insert into org values (10,'Dept 2',106000,8);
Insert into org values (11,'Area 2',null,2);
Insert into org values (12,'Office 1',null,11);
Insert into org values (13,'Dept 1',140000,12);
Code:
col a heading "Unit" format a20
col b heading "Budget" format $999,999
select lpad(' ',(level-1) * 3) ||name a, budget b
from org
start with parent_id is null
connect by prior id = parent_id;
Unit Budget
-------------------- ---------
Company A
Region 1
Area 1
Office 1
Dept 1 $100,000
Dept 2 $110,000
Dept 3 $105,000
Office 2
Dept 1 $112,000
Dept 2 $106,000
Area 2
Office 1
Dept 1 $140,000
13 rows selected.
Code:
Company A $673,000 <--- Roll up of its 1 Region
Region 1 $673,000 <--- Roll up of its 2 Areas
Area 1 $533,000 <--- Roll up of its 2 Offices
Office 1 $315,000 <--- Roll up of its 3 Depts
Dept 1 $100,000
Dept 2 $110,000
Dept 3 $105,000
Office 2 $218,000 <--- Roll up of its 2 Depts
Dept 1 $112,000
Dept 2 $106,000
Area 2 $140,000 <--- Roll up of its 1 Office
Office 1 $140,000 <--- Roll up of its 1 Dept
Dept 1 $140,000
Thanks in advance for any help you can provide.