我有两个表customer和hierarchy如下:
Customer Table Hierarchy Table
Pty Amount SID Parent Child
100 10 01 1 2
200 20 02 2 3
100 20 03 3 100
1 200
我想获得总父交易金额但父母没有任何金额 客户表中的数据。如何通过仅使用层次结构查询来映射两个表,并将所有子项的值都获取为父级。
我目前的查询如下,但不能正确发挥我的目的
Select Sum(c.amount),c.pty from customer c
right outer join hierarchy h on c.pty=h.child
where h.parent in (select (m.child) as parent from hierarchy m
Connect By Prior child=parent
start with m.child=1
) group by c.pty
Result is as follows:
Amount Pty
30 2
null 1
But When I pass 1 as parameter I should get
Amount Pty
50 1
When 2 is passed to the query, the result should be
Amount Pty
30 2
非常感谢任何帮助
答案 0 :(得分:1)
select root, sum(nvl(amount, 0)) s from (
select level, h.child, h.parent, c.amount, connect_by_root h.parent root
from customer c right join hierarchy h on c.pty = h.child
--start with h.parent = 1
connect by prior child = parent
) group by root;
如果您想要查找某个父母的总和,只需取消注释START WITH
connect_by_root 是一元运算符,显示层次结构的根值
此查询从层次结构表中的每一行开始,并查找所有子项
connect_by_root 有助于识别根父母