如何从oracle中的两个表中获取分层数据?


8

我有两个表table1和table2,我需要通过连接两个表进行分层输出。

表1包含三个类别CAT1,CAT2和CAT3,其中一个外键即F_ID,它是另一个表table2的主键,表2中又包含一个列,即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       9

现在,我需要以下格式的数据,其中每个类别和子类别都包含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      9

请帮我。

Answers:


6

使用分组集。您可以在这里尝试。

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 first

输出值

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  9

如果您喜欢null使用下划线而不是使用NVL

select 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 first

4
另一个选择group by cat1, rollup(cat2, cat3)
Andriy M

5
@AndriyM或:group by rollup(cat1, cat2, cat3) having grouping(col1)=0
ypercubeᵀᴹ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.