我是Oracle的新手,我想形成一个Oracle查询:
Id CrLmt Type Unit Price Amount Prev_bal NewBal
5-00001 100000 Sell 100 150 15000 100000 85000
Buy 75 600 45000 85000 130000
Buy 85 550 46750 130000 176750
Sell 60 1000 60000 176750 116750
5-00002 90000 Sell 100 400 40000 90000 50000
Buy 550 300 165000 50000 215000
Sell 300 1000 300000 215000 -85000
我的条件如下:
我尝试使用LAG函数来获取以前的值,但不知道如何在旅途中获取动态列的(NewBal)值。
答案 0 :(得分:1)
这是一个小例子,你必须适应你当前的结构。您需要在交易日期中获得总和的订单子句。
您只需要一个运行金额,您可以为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