根据sqlite中的条件进行汇总

ccgok5k5  于 2022-12-04  发布在  SQLite
关注(0)|答案(1)|浏览(152)

我有一个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
zyfwsgd6

zyfwsgd61#

使用SUM()窗口函数和条件聚合:

SELECT DISTINCT
       SUM(
         SUM(amount) - 
         CASE 
           WHEN TOTAL(amount < 0) < 3 
             OR TOTAL(CASE WHEN amount < 0 THEN amount END) >= -100 
           THEN 5 
           ELSE 0 
         END
       ) OVER () AS total
FROM transactions
GROUP BY strftime('%Y-%m', date);

请参阅demo

相关问题