Customer (parent table)
Id | Charge Amt |
---|---|
C1 | 10 |
C2 | 20 |
C3 | 30 |
C4 | 40 |
Payment (child table)
Id | pymt amt |
---|---|
C1 | 10 |
C2 | 5 |
C4 | 40 |
Select Id and pending balance from customer and payment tables
Pending balance validations:
- If payment amount is >= charge amount then set pending balances to 0
- If payment amount is less then set charge amount - payment amount to pending balance.
- If payment record not found then set charge amount to pending balances.
My query is not working for third(3) scenario:
I need output like:
Id | Pending bal |
---|---|
C1 | 0 |
C2 | 15 |
C3 | 30 |
C4 | 0 |
Query: Tried left outer join also but sum of payment is not working.
Select A.ID,
(SELECT (
CASE
WHEN (SUM(B.PYMT AMT) < A.CHARGE AMT)
THEN (A.CHARGE AMT - SUM(B.PYMT AMT))
ELSE 0 END)
FROM PYMT B
WHERE B.ID = A.ID)
FROM CUST A;