views:

409

answers:

3

Hi,

I have a SQLite table called posts. An example is shown below. I would like to calculate the monthly income and expenses.

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

For the income I have this query:

SELECT SUBSTR(date, 0,7) "month", total(amount) "income" FROM posts
WHERE amount > 0 GROUP BY month ORDER BY date;

It works fine:

month       income    
----------  ----------
2007-05     4877.0   
2007-06     8750.5   
2007-07     8471.0   
2007-08     5503.0

Now I need the expenses and I could of cause just repeat the first statement with the condition amount < 0, but I am wondering if there is an elegant way to get both income and expenses in one query?

+2  A: 

Not sure if SQL Lite supports CASE statements, but if it does you could do something like this.

SELECT SUBSTR(date, 0,7) "month"
, total(CASE WHEN Amount > 0 THEN Amount ELSE 0 END) "income" 
, -1 * total(CASE WHEN Amount < 0 THEN Amount ELSE 0 END) "expenses" 
FROM posts 
GROUP BY month 
ORDER BY date;
Kibbee
Thanks, this also works if one adds END to the CASE statements.
tiktuk
Yeah, in SQLite you have to END your CASE statements - (CASE WHEN Amount > 0 THEN Amount ELSE 0 END)
Jared Harley
Yeah, fixed that.
Kibbee
+4  A: 

Try something like this

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
Tetraneutron
Thanks, this works perfectly. And is very elegant :-) .
tiktuk
+1  A: 

Look into the UNION statement (bottom of the link). This will let you combine the results of two queries, generally in the form:

<SELECT_STATEMENT_1> UNION <SELECT_STATEMENT_2>
Wayne Koorts