我有一个sql表事务,具有如下形式:
amount date
1000 2020-01-05
-10 2020-01-13
-75 2020-01-19
-7 2020-01-25
2000 20202-03-10
-10 2020-03-12
...
我想把金额栏中的所有金额加起来,我必须为每个月加一个-5,因为我没有最小的3个金额带“-”,而且负数的总和〈= -100。我该怎么做呢?首先我做了:
SELECT date(date, 'start of month')
, count(amount), sum(amount)
from transactions
--condition that it only counts the negative amounts (that are the credit card payments)
where amount <0
group by
date(date, 'start of month')
返回表:
2020-01 3 -93
2020-03 1 -10
因此,在这种情况下,两个月都没有达到条件,该月将产生-5
因此结果将是:
balance
2888
1条答案
按热度按时间zyfwsgd61#
使用
SUM()
窗口函数和条件聚合:请参阅demo。