oracle 使用SQL的资产负债表

ilmyapht  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(139)

我们有一个表-交易如下-https://i.stack.imgur.com/BhGk5.jpg
我们需要有一个列'平衡',这将显示每个客户的余额后,他们有一个信贷/借记在他们的帐户。
示例1-假设客户A1的初始余额为0,如果“Credit”为300,则“Balance”列应显示为300。如果之后有100的“借方”,则应显示200,即300-100。
例2-假设客户B1的初始余额为0,如果“借方”为300,则余额列应显示为-300如果之后“贷方”为100,则应显示为-200,即-300+100
我不确定这是如何实现的。请协助。
以下是示例数据的脚本-

create table transactions (transaction_id number, customer_id varchar2(5), transaction_type varchar2(15), amount number);

    insert into transactions values(1,'A1', 'Credit',100)
    insert into transactions values(2,'A3', 'Credit',2000);
    insert into transactions values(3,'B1', 'Debit',300);
    insert into transactions values(4,'A1', 'Debit',1900);
    insert into transactions values(5,'A3', 'Debit',1200);
    insert into transactions values(6,'B1', 'Credit',1400);
    insert into transactions values(7,'C1', 'Credit',30000);
    insert into transactions values(8,'B1', 'Debit',2000);
    insert into transactions values(9,'A3', 'Credit',4000);
    insert into transactions values(10,'A1', 'Debit',200);
    insert into transactions values(11,'C1', 'Credit',300);

    select * from transactions;```

字符串

1tuwyuhd

1tuwyuhd1#

可以使用解析函数sum()

select t.*,
       sum(case when transaction_type = 'Credit' then amount else -amount end)
           over (partition by customer_id order by transaction_id) as balance
from transactions t

字符串

相关问题