问题
I want to get records out of sqlite database according to hours. following are my questions
1) I have to extract all data from sqlite for past one hour. I have tried following query but it provide me data for all the hours in present day
Query:
SELECT * FROM Table1 where Date >= datetime('now','-1 hours')
Where Table1 is my table name and Date is coloumn name of type DATETIME
Eg: there are following record in database
When I fire query in sqlite firefox browser tool it returns me
which I do not want.
What should be the query to get past 1 hour data from database
2) What should be query to get the value out of database according to every hours, like I have to get data for past 1 hour, then data of past 1-2 hour, the data of past 2-3 hour i.e an hour data between two hours?
Any Help will be appreciated.
回答1:
Use this query for question 1 -
`select * from Table1 where(Date between '(Select Date from Table1 order by Date asc limit 1)' and 'date1');`
date1 should be in formate yyyy-MM-dd hh:mm:ss
(for example 2015-10-21 08:00:00
).
In date1 you can put before 1 hour datetime.
it is working in SQLite Manager.
For question 2 - you have to get data for every hour separately using below query
select * from Table1 where(Date between 'date1' and 'date2');
回答2:
Finally I found the solution to my own question
Following is the code which worked for me
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;
}
}
I hope it will help someone in future
来源:https://stackoverflow.com/questions/33254848/getting-data-according-to-last-hours-from-sqlite