這是一個小例子,您將不得不適應您當前的結構。您將在交易中爲訂單條款訂購一個日期。
所有你需要的是一個正在運行的總和,你要麼增加信用額度爲new_balance或者你會採取上一行的old_balance
--TEST DATA
CREATE TABLE credit_limit (id varchar2(10), crlmt number);
CREATE TABLE transactions (transaction_type varchar2(4), unit number, price number, amount number, crlmt_id varchar2(10), date_transaction date);
INSERT INTO credit_limit values ('5-00001',100000);
INSERT INTO credit_limit values ('5-00002',90000);
INSERT INTO transactions values ('Sell',100,150,15000,'5-00001',sysdate-4);
INSERT INTO transactions values ('Buy',75,600,45000,'5-00001',sysdate-3);
INSERT INTO transactions values ('Buy',85,550,46750,'5-00001',sysdate-2);
INSERT INTO transactions values ('Sell',60,1000,60000,'5-00001',sysdate-1);
INSERT INTO transactions values ('Sell',100,400,40000,'5-00002',sysdate-3);
INSERT INTO transactions values ('Buy',550,300,165000,'5-00002',sysdate-2);
INSERT INTO transactions values ('Sell',300,1000,300000,'5-00002',sysdate-1);
--The query
select cr.id, cr.crlmt, tr.transaction_type, tr.unit, tr.price, tr.amount,
NVL(cr.crlmt + SUM(tr.amount*decode(tr.transaction_type,'Sell',-1,'Buy',1))
OVER (partition by cr.id order by cr.id, tr.date_transaction
rows between unbounded preceding and 1 preceding),Cr.crlmt) old_bal,
cr.crlmt + SUM(tr.amount*decode(tr.transaction_type,'Sell',-1,'Buy',1))
OVER (partition by cr.id order by cr.id, tr.date_transaction
rows between unbounded preceding and current row) new_bal
from
credit_limit cr
JOIN
transactions tr
ON cr.id=tr.crlmt_id
order by cr.id, tr.date_transaction
結果:
ID CRLMT TRAN UNI PRICE AMOUNT OLD_BAL NEW_BAL
5-00001 100000 Sell 100 150 15000 100000 85000
5-00001 100000 Buy 75 600 45000 85000 130000
5-00001 100000 Buy 85 550 46750 130000 176750
5-00001 100000 Sell 60 1000 60000 176750 116750
5-00002 90000 Sell 100 400 40000 90000 50000
5-00002 90000 Buy 550 300 165000 50000 215000
5-00002 90000 Sell 300 1000 300000 215000 -85000
你能格式化你的數據嗎? – JRG
JRG,現在好了嗎? – vknowth
是否只有一張桌子上的東西?或者你的信用額度是否有表格,以及是否有涉及信用額度表的交易? – LauDec