在 SQL 查询中结转/结转余额
Posted
技术标签:
【中文标题】在 SQL 查询中结转/结转余额【英文标题】:Carry forward / Bring forward balance in SQL query 【发布时间】:2020-09-08 14:45:40 【问题描述】:我创建了一个如下表:
Member_ID | Amount | BringForward | Balance | DateTime
101 -100 2020-08-01 13:12:02.113
101 -200 2020-08-01 14:15:23.115
101 300 2020-08-02 10:25:15.315
101 500 2020-08-05 08:47:56.286
我想添加BringForward和Balance的数据,BringForward会将前一天的总金额结转(如果日期是8月1日,它将得到从数据第一天到31的所有总金额七月)。余额是BringForward - 金额。
我的期望是:
Member_ID | Amount | BringForward | Balance | DateTime
101 -100 0 100 2020-08-01 13:12:02.113
101 -200 0 200 2020-08-01 14:15:23.115
101 300 -300 0 2020-08-02 10:25:15.315
101 500 0 -500 2020-08-05 08:47:56.286
我试过的是:
select MP.MEMBER_ID AS Member_ID,
CONCAT(MP.AMT_TXN , MP.AMT_TXN_EX) AS Amount,
sum(cast(concat(AMT_TXN,amt_txn_ex) as decimal)) over (order by mp.create_date) AS BringForward,
(sum(cast(concat(AMT_TXN,amt_txn_ex) as decimal)) over (order by mp.create_date) - CONCAT(MP.AMT_TXN , MP.AMT_TXN_EX)) AS Balance,
MP.CREATE_DATE AS DateTime
from MEMBER_TRANSFER MP
结果是:
Member_ID | Amount | BringForward | Balance | DateTime
101 -100 -100 0 2020-08-01 13:12:02.113
101 -200 -300 -100 2020-08-01 14:15:23.115
101 300 100 -200 2020-08-02 10:25:15.315
101 500 800 300 2020-08-05 08:47:56.286
MEMBER_TRANSFER 表:
MEMBER_ID | AMT_TXN | AMT_TXN_EX | CREATE_DATE
101 -100 2020-08-01 13:12:02.113
101 -200 2020-08-01 14:15:23.115
101 300 2020-08-02 10:25:15.315
101 500 2020-08-05 08:47:56.286
【问题讨论】:
【参考方案1】:我认为您需要窗口函数和范围规范:
select
member_id,
amount,
coalesce(sum(coalesce(amt_txn, 0) + coalesce(amt_txn_ex, 0)) over(
partition by member_id
order by datetime
range between unbounded preceding and interval 1 day preceding
), 0) bringforward,
coalesce(sum((coalesce(amt_txn, 0) + coalesce(amt_txn_ex, 0)) over(
partition by member_id
order by datetime range between unbounded preceding and interval 1 day preceding
), 0) - (coalesce(amt_txn, 0) - coalesce(amt_txn_ex, 0) balance
from member_transfer m
【讨论】:
“间隔”附近有一个错误,即语法不正确。 (“间隔”一词下方出现红色下划线)您知道如何解决这个问题吗? @Mouris:您是否尝试运行查询?您到底遇到了哪个错误?以上是关于在 SQL 查询中结转/结转余额的主要内容,如果未能解决你的问题,请参考以下文章