查询最后一天,上周,上个月SQLite

时间:2012-05-08 18:21:48

标签: database sqlite datetime

我在Android SQLite DB中有这个表:

CREATE TABLE statistics (subject TEXT, hits INTEGER, fails INTEGER, date DATE)

date字段中,datetime('now', 'localtime')存储在每个寄存器中。

现在我必须查询最后一天,上周和上个月的寄存器以显示一些统计信息。 我一直在尝试这样的事情

    SELECT Timestamp, datetime('now', '-1 week') FROM statistics WHERE TimeStamp < datetime('now', '-1 week') 

和这个

    SELECT * FROM statistics WHERE date BETWEEN datetime('now', localtime') AND datetime ( 'now', '-1 month')

并且不起作用:(

我该怎么做?

我可以通过简单地在虚拟设备模拟器中转发日期来检查查询是否正常吗?

谢谢!

6 个答案:

答案 0 :(得分:27)

我找到了这个解决方案。我希望它适合你。

最后一天:

SELECT * FROM statistics WHERE date BETWEEN datetime('now', 'start of day') AND datetime('now', 'localtime');

上周:

SELECT * FROM statistics WHERE date BETWEEN datetime('now', '-6 days') AND datetime('now', 'localtime');

上个月:

SELECT * FROM statistics WHERE date BETWEEN datetime('now', 'start of month') AND datetime('now', 'localtime');

答案 1 :(得分:4)

这段代码可以让你上个月

SELECT * 
FROM statistics 
WHERE date >= date('now','start of month','-1 month')
AND date < date('now','start of month')

答案 2 :(得分:1)

SELECT * 
FROM statistics 
WHERE date >= date('now','start of month','-1 months')
AND date < date('now','start of month')

在更多月份,是“月份” ,而不是月份

答案 3 :(得分:0)

此代码有望带来前一周的记录

SELECT  * FROM  order_master
WHERE strftime('%Y-%m-%d',om_date) >= date('now','-14 days') AND 
strftime('%Y-%m-%d',om_date)<=date('now') order by om_date LIMIT 6

答案 4 :(得分:0)

SELECT 
max(date(date, 'weekday 0', '-7 day')) WeekStart,
max(date(date, 'weekday 0', '-1 day')) WeekEnd,date 
FROM table;

答案 5 :(得分:0)

您可以创建日历,然后从中获取时间戳

final Calendar todayCalendar = Calendar.getInstance();
final long todayTimestamp = todayCalendar.getTime().getTime();
todayCalendar.add(Calendar.DAY_OF_YEAR, -7);
final long aWeekAgoTimestamp = todayCalendar.getTime().getTime();
final String selection = TABLE_COLUMN_DATE_CREATED + " BETWEEN " + aWeekAgoTimestamp + " AND " + todayTimestamp;