使用 SQLite,我想為一個帳戶事務表創建一個視圖,該表有一個附加列“余額”,它顯示了該 account_id 的該事務之后的余額。我想它可能被稱為按帳戶的流動余額。
表格示例:
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;
uj5u.com熱心網友回復:
您可以嘗試使用視窗函式的PARTITION BY account_idinOVER子句。
磁區由 window-defn 中 PARTITION BY 子句的所有項具有相同值的所有行組成。
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/439851.html
上一篇:如何在電子郵件中查找單詞的位置并僅獲取電子郵件的一部分?
下一篇:跨多個資料庫運行SQL
