2010-01-22 94 views
2

我有兩個數據庫表Fine和Fine_payment。 精有字段
* fine_id [pk]
* fine_amount。SQL計算(Oracle)

Fine_payment有場
* fine_payment_id [PK]
* fine_id
*支付金額

所以每精細可以有多個付款。我將如何選擇那些尚未完全支付的罰款並顯示未付款額?

Oracle DB。

回答

4
select fine_id, fine_amount 
--------------------------------------------------------------- 
-- add a coalesce here, in case "payments" returns a NULL match 
--------------------------------------------------------------- 
, (fine_amount - coalesce(payments.already_paid, 0)) as outstanding_amount 
from Fine left outer join 
(
    select fine_id 
    , sum(coalesce(payment_amount, 0)) as already_paid 
    from Fine_payment 
    group by fine_id 
) payments 
on Fine.fine_id = payments.fine_id 
where Fine.fine_amount <> coalesce(payments.already_paid, 0) 

編輯inner joinleft outer join

+0

謝謝,有小錯字,應該合併(payment_amount,0)我想。 我如何修改這個以解決沒有任何罰款付款的情況?我的第一個想法是留在外部聯接,但這似乎並不奏效。 – Illotus 2010-01-22 11:57:50

+0

感謝您注意到 - 我會更正它。 LOJ也應該工作。 – davek 2010-01-22 12:26:03

1

,因爲我不是在使用SQL中的一些非常先進的方法是多完美的替代,我有什麼是below.it可能時間服用查詢和我堅信我們可以調整。

SELECT a.fine_id,b.SUM_of_amount_paid,(a.fine_amount-b.SUM_of_amount_paid) amount_left_to_be_paid 
FROM 
    (SELECT fine_id,fine_amount FROM fine) a, 
    (SELECT fine_id,SUM(fine_payment_amount) SUM_of_amount_paid FROM fine_payment GROUP BY fine_id) b 
WHERE a.fine_id=b.fine_id 
AND 
(a.fine_amount-b.SUM_of_amount_paid) >0