使用 MySQL 中的 ID 和日期进行累计和

Making cumulative sum with ids and dates in MySQL

假设我有这个:

id transactiondate transactiontag clientid transactionvalue
1 2020-12-28 pizza 0 29.99
2 2020-12-29 payment 0 -39.99
3 2020-12-28 cheese 0 -109.99
4 2020-12-28 cheese 0 -109.99
5 2020-12-28 pizza 1 -19.99
6 2020-12-28 cheese 1 -18.99
7 2020-12-28 salary 1 58.99
8 2020-12-29 salary 1 38.99

所以我有所有交易的 ID,交易的时间和支付的金额,我需要做的是每个日期和每个人的累计总和,所以答案应该是这样的:

这个代码 -> SELECT distinct accountid, transactiondate, SUM(transactionvalue) OVER(ORDER BY transactiondate) AS cumulative_sum FROM acc_transactions where accountid = 1; 给我这个

clientid date cumulative_sum
1 2020-12-28 20.01
1 2020-12-29 59.00

问题是,对于客户端 1 和 0,我都需要这个,到目前为止我已经尽了一切努力!现在需要英雄哈哈!

正确答案示例↓

clientid date cumulative_sum
1 2020-12-28 20.01
1 2020-12-29 59.00
0 2020-12-28 -189.99
0 2020-12-29 -229.98

首先你想要一个每日汇总:

select accountid, transactiondate, 
    sum(transactionvalue) as transactionvalue
from acc_transactions 
group by accountid, transactiondate
order by accountid, transactiondate

然后,您可以在其上使用 window 函数:

select accountid, transactiondate, 
    sum(sum(transactionvalue)) 
        over(partition by accountid order by transactiondate) 
        as cumulative_sum
from acc_transactions
group by accountid, transactiondate
order by accountid, transactiondate