我有一个名为的SQLite表posts
.一个例子如下所示.我想计算每月的收入和支出.
accId date text amount balance ---------- ---------- ------------------------ ---------- ---------- 1 2008-03-25 Ex1 -64.9 3747.56 1 2008-03-25 Shop2 -91.85 3655.71 1 2008-03-26 Benny's -100.0 3555.71
对于收入我有这个查询:
SELECT SUBSTR(date, 0,7) "month", total(amount) "income" FROM posts WHERE amount > 0 GROUP BY month ORDER BY date;
它工作正常:
month income ---------- ---------- 2007-05 4877.0 2007-06 8750.5 2007-07 8471.0 2007-08 5503.0
现在我需要费用,我可以因为重复第一个条件的条件amount < 0
,但我想知道是否有一种优雅的方式来获得一个查询中的收入和费用?
尝试这样的事情
select substr(date, 0,7) "Month", total(case when a > 0 then a else 0 end) "Income", total(case when a < 0 then a else 0 end) "Expenses" from posts group by month