Mysql SQL查询中的结转/结转余额
我创建了一个如下表:Mysql SQL查询中的结转/结转余额,mysql,sql,sum,window-functions,mysql-8.0,Mysql,Sql,Sum,Window Functions,Mysql 8.0,我创建了一个如下表: 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
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日,则将获得从数据第一天到7月31日的所有金额总和)。余额为正向-金额
我所期望的是:
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_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
我认为您需要窗口功能和范围规范:
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
“interval”附近存在语法不正确的错误。(红色下划线出现在单词“interval”下)你知道如何解决这个问题吗?@Mouris:你试过运行这个查询吗?您得到的确切错误是什么?