获取上周,月份和年份记录的SQL语句

时间:2014-09-06 12:09:29

标签: java android sql sqlite datetime

我在尝试从SQLite数据库获取最后周,月和年记录时遇到了一些问题。我的数据库表:

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 周,月和年。有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您已经在使用日期修饰符。 再减去一周/月/年:

... 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')