如何使用 SQLite 创建一个显示 运行 账户交易余额的视图

How to make a view showing a running transaction balance by account with SQLite

我想使用 SQLite 创建一个帐户交易 table 的视图,其中有一个附加列“余额”,显示 account_id 交易后的余额。我猜它可能被称为 运行 账户余额。

table 示例:

id |   dateof   | transaction_amount | account_id
 1 | 2022-02-01 |       9500.00      |     1 
 2 | 2022-02-02 |       -500.00      |     1 
 3 | 2022-02-02 |        500.00      |     2
 4 | 2022-02-04 |         10.00      |     2
 5 | 2022-02-05 |         50.00      |     1 

查看示例:

id |   dateof   | transaction_amount | account_id | balance
 1 | 2022-02-01 |       9500.00      |     1      | 9500.00
 2 | 2022-02-02 |       -500.00      |     1      | 9000.00
 3 | 2022-02-02 |        500.00      |     2      |  500.00
 4 | 2022-02-04 |         10.00      |     2      |  510.00
 5 | 2022-02-05 |        -50.00      |     1      | 8950.00

使用以下 sql,我能够创建 运行 余额,但我不知道如何根据帐户 ID 生成余额结果:

create view acct_txn_v as
with t as (
select * from acct_txn
)
select t.*, sum(amt) over (order by dateof, id) as balance
from t;

您可以尝试在 window 函数的 OVER 子句中使用 PARTITION BY account_id

A partition consists of all rows that have the same value for all terms of the PARTITION BY clause in the window-defn.

create view acct_txn_v as
with t as (
select * from acct_txn
)
select t.*, sum(amt) over (PARTITION BY account_id  order by dateof, id) as balance
from t;