2014-11-06 54 views
0

我有兩個表的客戶和層次結構,如下的最高父量:如何從甲骨文

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 

我想獲得總父交易金額,但父母並沒有在客戶表中的任何 數據。如何僅通過使用層次結構查詢來映射兩個表,並將所有子元素的值獲取到父級。

我當前的查詢如下但是,如果你想找到一個特定的父母只是取消註釋START WITH總和不爲我的目的適當

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

解釋規則的輸出。 – 2014-11-06 07:00:17

回答

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; 

connect_by_root是一個一元運算符,它顯示了層次結構的根值

這個查詢開始與分級表的每一行,並認爲所有的孩子

CONNECT_BY_ROOT有助於找出根本父

+0

感謝您的回覆。此查詢工作正常,並給我全部金額的詳細信息。:)但如何篩選列表只有選定的項目的記錄,而不使用開始?示例:一次只顯示父母1或父母2的金額。 – psobhan 2014-11-06 08:29:01

+1

@psobhan ...)其中根(1,2)根組; – Multisync 2014-11-06 09:54:54