Reputation: 137
I need to find the remaining amount for each credit no. The expected result is this:
CREDIT_NO CREDIT_TYPE CREDIT_AMOUNT TOTAL_A REMAINING_AMT FINAL_TOTAL_PER_BILL
A1 W 100 1000 900 600
A1 X 100 1000 800 600
A1 Y 100 1000 700 600
A1 Z 100 1000 600 600
B1 X 100 2000 1900 1700
B1 Y 100 2000 1800 1700
B1 Z 100 2000 1700 1700
Here's the query I have done so far (please pardon the noob):
WITH TEMP AS
(SELECT 1 ID,
'A1' CREDIT_NO,
'X' CREDIT_TYPE,
100 CREDIT_AMOUNT,
1000 TOTAL_A
FROM DUAL
UNION ALL
SELECT 2, 'A1' , 'Y', 100, 1000 FROM DUAL
UNION ALL
SELECT 4, 'A1' , 'Z', 100, 1000 FROM DUAL
UNION ALL
SELECT 3, 'B1', 'X', 100, 2000 FROM DUAL
UNION ALL
SELECT 5, 'B1', 'Y', 100, 2000 FROM DUAL
UNION ALL
SELECT 6, 'B1', 'Z', 100, 2000 FROM DUAL
UNION ALL
SELECT 7, 'A1', 'W', 100, 1000 FROM DUAL
)
SELECT
TEMP1.CREDIT_NO ,
TEMP1.CREDIT_TYPE,
TEMP1.CREDIT_AMOUNT ,
TEMP1.TOTAL_A ,
CASE
WHEN TEMP1.CREDIT_NO = (LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) ) -- set remaining CREDIT_AMOUNT
OR (LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) ) IS NULL
THEN TEMP1.TOTAL_A - (SUM(TEMP1.CREDIT_AMOUNT) OVER ( ORDER BY TEMP1.CREDIT_NO ROWS BETWEEN
UNBOUNDED PRECEDING
AND CURRENT ROW ) )
WHEN TEMP1.CREDIT_NO <> -- new bill, new total CREDIT_AMOUNT
(LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) )
THEN TEMP1.TOTAL_A - TEMP1.CREDIT_AMOUNT
END AS REMAINING_AMT
,TEMP1.TOTAL_A - (SUM(TEMP1.CREDIT_AMOUNT) OVER (PARTITION BY CREDIT_NO)) AS FINAL_TOTAL_PER_BILL
FROM TEMP TEMP1
ORDER BY CREDIT_NO, CREDIT_TYPE
My problem is I don't know how to compute for the remaining amount for the 2nd credit no. The result of the above query is:
CREDIT_NO CREDIT_TYPE CREDIT_AMOUNT TOTAL_A REMAINING_AMT FINAL_TOTAL_PER_BILL
A1 W 100 1000 900 600
A1 X 100 1000 800 600
A1 Y 100 1000 700 600
A1 Z 100 1000 600 600
B1 X 100 2000 1900 1700
B1 Y 100 2000 1400 1700
B1 Z 100 2000 1300 1700
Is it possible to get a running remaining amount without using a stored procedure? I tried basing it on the rownum but it is not sequential.
Even though I have found similar questions to this (Link 1, Link 2, Link 3) (I'm still going over the third link though), I hope you guys can help me.
Upvotes: 2
Views: 502
Reputation: 17643
use a running subtotal, and be careful at partition
clause as:
select credit_no, credit_type,
total_a - sum(credit_amount) over (partition by credit_no order by id) as remaining_credit,
total_a,
total_a - sum(credit_amount) over (partition by credit_no) as FINAL_TOTAL_PER_BILL
from temp
Upvotes: 2