根据从 sqlite 的最后几个小时获取数据

Getting data according to last hours from sqlite

我想按小时从sqlite数据库中取出记录。以下是我的问题

1) 我必须从 sqlite 中提取过去一小时的所有数据。我尝试了以下查询,但它为我提供了当天所有时间的数据

查询:

SELECT * FROM Table1 where Date >= datetime('now','-1 hours')

其中 Table1 是我的 table 名称,日期是 DATETIME 类型的列名称

例如:数据库中有如下记录

当我在 sqlite firefox 浏览器工具中触发查询时 returns 我

我不想要。

从数据库中获取过去 1 小时数据的查询应该是什么

2) 应该查询什么来根据每小时从数据库中获取值,比如我必须获取过去 1 小时的数据,然后是过去 1-2 小时的数据,过去 2-3 小时的数据小时,即两个小时之间的一个小时数据?

任何帮助将不胜感激。

使用此查询回答问题 1 -

`select * from Table1 where(Date between '(Select Date from Table1 order by Date asc limit 1)' and 'date1');`

date1 的格式应为 yyyy-MM-dd hh:mm:ss(例如 2015-10-21 08:00:00)。 在 date1 中,您可以在 1 小时之前输入日期时间。

它正在 SQLite 管理器中工作。

对于问题 2 - 您必须使用以下查询分别获取每小时的数据

select * from Table1 where(Date between 'date1' and 'date2'); 

我终于找到了自己问题的答案

以下是对我有用的代码

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        String startDate = dateFormat.format(date);
        String endDate = "";
        for (int i = 1; i <= 24; i++) {
            System.out.println("Start Date:- " + startDate);
            calendar.add(Calendar.HOUR_OF_DAY, -1);
            date = calendar.getTime();
            endDate = dateFormat.format(date);
            System.out.println("End Date:- " + endDate);
            String data = dbAdapter.getOutDoorHourlyData(startDate, endDate);
            System.out.println("Hourly Average:- " + data);
            startDate = endDate;
            endDate = "";
        }

public String getOutDoorHourlyData(String startDate, String endDate) {
        double outdoorHourly = 0;

        Cursor cursor = _sqliteDB.rawQuery("Select AVG("
                + COLOUMN_NAME + ") from (Select * FROM "
                + TABLE_NAME + " where " + COLOUMN_NAME + " >= '"
                + endDate + "' and " + COLOUMN_NAME + " < '" + startDate
                + "')", null);

        try {

            if (cursor != null) {
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    do {
                        outdoorHourly = cursor.getDouble(0);
                    } while (cursor.moveToNext());
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String hourlyData = decimalFormat.format(outdoorHourly);
        hourlyData = hourlyData.replace(",", ".");
        return hourlyData;

    }

 }

希望对以后的人有所帮助