7.15 更改累计和中的值

问题:
根据另一列中的值修改累计和中的值。假设一个场景,要显示信用卡账号的事务处理历史以及每次事务处理之后的当前余额。使用下面的视图:
create view v (id,amt,trx)
as 
select 1,100,'PR' from t1 union all
select 2,100,'PR' from t1 union all
select 3, 50,'PY' from t1 union all
select 4,100,'PR' from t1 union all
select 5,200,'PY' from t1 union all
select 6, 50,'PY' from t1;

ID列唯一标识每次事务处理。AMT列表示每次事务处理(取款或存款)涉及的金额。TRX列定义了事务处理的类型;取款是“PY”,存款是“PR”。如果TRX值是PY,则想要从累计和中减去AMT值代表的金额;如果TRX值是PR,则想要给累计和加上AMT值代表的金额。

select case when v1.trx='PY'
then 'PARMENT'
else 'PURCHASE'
end as trx_type,
v1.amt,
(select sum(
case when v2.trx='PY'
then -v2.amt else v2.amt
end)
from v v2
where v2.id<=v1.id) as balance
from v v1;

原文地址:https://www.cnblogs.com/liang545621/p/7523286.html