2013-03-31 61 views
0

我想了解我的數據庫中每月的餘額摘要。該表具有以下字段SQLite ROLLUP查詢

tran_date 

type (Income or Expense) 

amount 

我能得到儘可能獲取總和爲每種類型的每個月,但希望整個月的總和。這是我當前的查詢:

SELECT DISTINCT strftime('%m%Y', tran_date), type, SUM(amount) FROM tran WHERE exclude = 0 GROUP BY tran_date, type 

這將返回

032013 Income 100 

032013 Expense 200 

我想在一行的總結,在這個例子中032013 -100。

回答

1

只需使用正確的group by。該使用條件的聚集,假設你想「收入 - 費用」:

SELECT strftime('%m%Y', tran_date), type, 
     SUM(case when type = 'Income' then amount when type = 'Expense' then - amount end) 
FROM tran WHERE exclude = 0 
GROUP BY tran_date; 

如果你只想在充分總結,那麼這是比較容易:

SELECT strftime('%m%Y', tran_date), type, 
     SUM(amount) 
FROM tran WHERE exclude = 0 
GROUP BY tran_date; 

你原來的查詢返回類型行,因爲「類型「在group by子句中。 (幾乎)不需要group by

+0

謝謝!我只是不確定如何計算這兩種類型。 – Carl