snippetMinor
How to get hierarchical data from two tables in oracle?
Viewed 0 times
oracletablestwohierarchicalgethowfromdata
Problem
I have two tables table1 and table2, I need hierarchical output by joining of both of the tables.
Table1 contains three categories CAT1, CAT2 and CAT3 with one Foreign key i.e. F_ID which is a primary key of another table table2 which contains one more column i.e.VAL.
Now i need the data in the below format, where every category and sub-category contains the total sum of VAL.
Please help me.
Table1 contains three categories CAT1, CAT2 and CAT3 with one Foreign key i.e. F_ID which is a primary key of another table table2 which contains one more column i.e.VAL.
TABLE 1
-----------------
CAT1 CAT2 CAT3 F_ID
A a aa 1
A a ab 2
A b ba 3
A b bb 4
B c ca 5
B c cb 6
B d da 7
TABLE 2
-------------------
F_ID VAL
1 4
2 6
3 4
4 1
5 6
6 6
7 9Now i need the data in the below format, where every category and sub-category contains the total sum of VAL.
Need Data in below Format from the above table
----------------------------------------------
A - - 15
A a - 10
A a aa 4
A a ab 6
A b - 5
A b ba 4
A b bb 1
B - - 21
B c - 12
B c ca 6
B c cb 6
B d - 9
B da da 9Please help me.
Solution
Use grouping sets. You can try it here.
OUTPUT
If you prefer underscore than
select cat1, cat2, cat3, sum(val) as val
from t1 join t2 on t1.f_id = t2.f_id
group by grouping sets ((cat1),(cat1, cat2),(cat1, cat2, cat3))
order by cat1, cat2 nulls first, cat3 nulls firstOUTPUT
cat1 cat2 cat3 val
A 15
A a 10
A a aa 4
A a ab 6
A b 5
A b ba 4
A b bb 1
B 21
B c 12
B c ca 6
B c cb 6
B d 9
B d da 9If you prefer underscore than
null use NVLselect cat1, nvl(cat2,'_') as cat2, nvl(cat3, '_') as cat3, sum(val)
from t1 join t2 on t1.f_id = t2.f_id
group by grouping sets ((cat1),(cat1, cat2),(cat1, cat2, cat3))
order by cat1, cat2 nulls first, cat3 nulls firstCode Snippets
select cat1, cat2, cat3, sum(val) as val
from t1 join t2 on t1.f_id = t2.f_id
group by grouping sets ((cat1),(cat1, cat2),(cat1, cat2, cat3))
order by cat1, cat2 nulls first, cat3 nulls firstcat1 cat2 cat3 val
A 15
A a 10
A a aa 4
A a ab 6
A b 5
A b ba 4
A b bb 1
B 21
B c 12
B c ca 6
B c cb 6
B d 9
B d da 9select cat1, nvl(cat2,'_') as cat2, nvl(cat3, '_') as cat3, sum(val)
from t1 join t2 on t1.f_id = t2.f_id
group by grouping sets ((cat1),(cat1, cat2),(cat1, cat2, cat3))
order by cat1, cat2 nulls first, cat3 nulls firstContext
StackExchange Database Administrators Q#149801, answer score: 7
Revisions (0)
No revisions yet.