2014-09-06 53 views
0

我在嘗試從SQLite數據庫獲取上一個周,月和年記錄時遇到了一些問題。我的數據庫表:SQL Statement獲取上週,月和年的記錄

enter image description here

我只設法獲得今天的紀錄,昨天,周,個月和年。

對於本週:

SELECT SUM(amount) AS Total, (substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date,1, 2)) AS currentDate FROM TransactionRec WHERE currentDate BETWEEN DATE('now', '-7 days') AND Date('now') GROUP BY currentDate 

這個月:

SELECT SUM(amount) AS Total, (substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date,1, 2)) AS currentDate FROM TransactionRec WHERE currentDate BETWEEN DATE('now', 'start of month') AND Date('now') GROUP BY currentDate 

對於今年:

SELECT SUM(amount) AS Total, (substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date,1, 2)) AS currentDate FROM TransactionRec WHERE currentDate BETWEEN DATE('now', '-1 year') AND Date('now')GROUP BY currentDate 

但我不知道如何改變SQL語句來獲得last周,月和年。有任何想法嗎?

在此先感謝。

+0

檢查這個參考http://www.sqlite.org/lang_datefunc.html。以及日期時間字符串如何格式化以使用日期時間函數。 – user3455363 2014-09-06 12:30:43

+0

順便說一句,SQLite不支持strftime(),因爲它會使程序沒有響應 – 2014-09-06 12:32:11

+1

如果正確使用'strftime()',它就可以正常工作。 – 2014-09-06 12:35:15

回答

2

您已經在使用日期修飾符。 只是減去一個星期/月/年:

... BETWEEN date('now', '-14 days') AND date('now', '-7 days') 
... BETWEEN date('now', 'start of month', '-1 months') AND date('now', 'start of month', '-1 days') 
... BETWEEN date('now', '-2 years') AND date('now', '-1 years') 
+0

它適用於上週和一年,但不是一個月。你有什麼想法? – 2014-09-06 12:51:32

+0

你有什麼想法得到最後一個月導致它不工作:( – 2014-09-06 13:18:49

+0

'選擇日期('現在','-1個月');'→'2014-08-06'。什麼不工作? – 2014-09-06 13:23:57