2014-09-06 47 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