I have a sqlite database. I have three columns:_id, date, value.
I now want to extract a count of the _id:s depending on the day in the date, and calculate an average of the int value. This is for an Android app.
So I want to "select the day in date and for each day ( for sixty days), count how many _id:s there are for this day. Finally calculate the average of value.
I guess it is something like :
"SELECT DATE('now' 'days[i]') as date, COUNT(_id) as count, AVG(value) as vl FROM v_efforts WHERE DATE(v_efforts.date) = DATE('now' 'days[i]')";
But I can't get the 'days[i]' to work. I don't know how i can get this value to increase to sixty, and then how I can store the count and vl for each of these sixty days.
THanks a lot!
You'll want to use a GROUP BY expression to aggregate the entries by date. It's not quite clear whether you're looking for the last 60 days of entries in the database, or the entries from the last 60 real days (which would only be the same if you can assume that there are entries every day).
For the former (last 60 days which had database entries), you can use a LIMIT clause:
SELECT date,COUNT(_id),AVG(value) FROM v_efforts GROUP BY date ORDER BY date DESC LIMIT 60;
For the latter (last 60 real days), you can use WHERE:
SELECT date,COUNT(_id),AVG(value) FROM v_efforts WHERE date>DATE('now','-60 days') GROUP BY date ORDER BY date DESC;
The docs for Version 3 are pretty decent:
http://www.sqlite.org/lang_datefunc.html
I would look at the block that deals with the built in date time functions. Since SQLite doesn't support an actual date datetype:
Compute the current date:
SELECT date('now');
Compute the last day of the current month:
SELECT date('now','start of month','+1
month','-1 day');
Compute the date and time given a unix timestamp 1092941466.
SELECT datetime(1092941466,
'unixepoch');
Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.
SELECT datetime(1092941466,
'unixepoch', 'localtime');
Compute the current unix timestamp.
SELECT strftime('%s','now');
Compute the number of days since the signing of the US Declaration of Independence.
SELECT julianday('now') -
julianday('1776-07-04');
Compute the number of seconds since a particular moment in 2004:
SELECT strftime('%s','now') -
strftime('%s','2004-01-01 02:34:56');
Compute the date of the first Tuesday in October for the current year.
SELECT date('now','start of year','+9
months','weekday 2');
Compute the time since the unix epoch in seconds (like strftime('%s','now') except includes fractional part):
SELECT (julianday('now') -
2440587.5)*86400.0;
Related
I have dates stored in my Database in a dd/mm/yyyy format and I am looking to only show items where the date is equal to or great than today.
I have tried WHERE date(fixtures.date) >= date('now') but I got no results.
Below is my query, any help would be greatly appreciated
SELECT fixtures.id,
fixtures.team_1_id,
fixtures.team_2_id,
fixtures.date,
fixtures.time,
fixtures.pitch,
teams.team_name,
teams_1.team_name AS awayTeam,
leagues.league_name
FROM fixtures
INNER JOIN teams
ON fixtures.team_1_id = teams.id
INNER JOIN teams AS teams_1
ON fixtures.team_2_id = teams_1.id
INNER JOIN teams_vs_leagues
ON teams.id = teams_vs_leagues.team_id
INNER JOIN leagues
ON teams_vs_leagues.league_id = leagues.id
WHERE date(fixtures.date) >= date('now')
ORDER BY fixtures.date DESC
Why do you say your dates are store in dd/mm/yyyy format? According to SQLite docs
1.2 Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
Basically this query won't work
select 1 where '01-08-2016' >= date('now')
but this will
select 1 where '2016-08-01'>= date('now')
So can you verify if your date fixtures.date is format as 'yyyy-MM-dd' otherwise your query won't work. Additionally remember to use date('now', 'localtime') to get your local time.
If your date is well formated you can try to do something like
SELECT fixtures.id
FROM fixtures
WHERE fixtures.date >= date('now')
if you do get results with this, then the joins are not matching any row.
For further information you can check this answer
In my database dates is stored in miliseconds as string. How to query unique dates considering only month and day and count how many date share same day?
Divide by 1000 to get seconds, then use the unixepoch modifier to get date, and use strftime to output only the year and month:
SELECT strftime('%Y-%m', DateMillis / 1000, 'unixepoch'),
COUNT(*)
FROM MyTable
GROUP BY 1
If you want to store a date, use date type. Sqlite may not have it. But please, do not use it as string! I would suggest you to store integer to store miliseconds sice epoch. Use bindLong() and such. Unfortunately, you have to make some computations yourself in code. Just compute first and last milisecond of each day. Then you would be able to use WHERE timestamp BETWEEN first_day_milisecond AND last_day_milisecond, using even indexes.
You can select min and max of timestamp to try only days between them.
If you need to do this frequently or over a lot of data, I suggest to store date in multiple columns as integers for year, month, day. Depends on what you have to do with time, miliseconds since midnight. Or more columns of hour, minute, second and miliseconds.
I think it is much easier to format string date from bunch of numbers than parsing those numbers from a string. Definitely easier to compare them inside database.
I want to make a query to get records between specified hours. For example, i want to get all records between 00:00 and 01:00 for all days. So, the date does not matter but hours. How to do that?
I have done this, but it only return for certain dates.
Select name from my_table where date_column> beginning and date_column< end
Here beginning and end are in millisecond. Also my date_column is stored in millisecond format.
Use strftime():
Select name
from my_table
where strftime('%H', date_column) = '00';
This just checks the hour. You could use '%H:%M:%S' if you wanted more granularity.
EDIT:
You do not have a date time value. You have something else. It looks like a Unix epoch time measured in milliseconds rather than seconds. If so, the following should work:
Select name, datetime(date_column/1000, 'unixepoch')
from my_table
where strftime('%H', datetime(date_column/1000, 'unixepoch')) = '19';
However, none of the times are at hour 3. You may need to convert using your localtime.
I store date from Calendar.getTimeInMilliseconds() in SQLite DB.
I need to mark first rows by every month in SELECT statement, so I need convert time in milliseconds into any date format using SQLite function only. How can I avoid this?
One of SQLite's supported date/time formats is Unix timestamps, i.e., seconds since 1970.
To convert milliseconds to that, just divide by 1000.
Then use some date/time function to get the year and the month:
SELECT strftime('%Y-%m', MillisField / 1000, 'unixepoch') FROM MyTable
Datetime expects epochtime, which is in number of seconds while you are passing in milliseconds. Convert to seconds & apply.
SELECT datetime(1346142933585/1000, 'unixepoch');
Can verify this from this fiddle
http://sqlfiddle.com/#!5/d41d8/223
Do you need to avoid milliseconds to date conversion or function to convert milliseconds to date?
Since sqlite date functions work with seconds, then you can try to
convert milliseconds in your query, like this
select date(milliscolumn/1000,'unixepoch','localtime') from table1
convert millis to seconds before saving it to db, and then use date function in sql query
I have seen number of post about storing date.
I am still not getting the fine and exact approach about saving it to a sqlite database.
I am able to store it, but during sorting I need to consider only month and day just like birthday where years doesn't matter.
What will be the query if I want to get the row whose date is 2 or 3 days in advance, like 2nd march row if searched on 28 Feb?
You should start by checking out the SQLite documentation of date & time functions.
For instance, to solve your problem "And what will be the query if i want to get the row whose date is 2 or 3 days in advance" you'd use julian day calculations, such as this example that you can execute directly in the sqlite3 shell:
create TABLE example (_id INTEGER PRIMARY KEY NOT NULL, date TEXT NOT NULL);
insert into example (date) values ('2011-01-02');
insert into example (date) values ('2011-04-02');
insert into example (date) values ('2012-02-26');
insert into example (date) values ('2012-02-27');
insert into example (date) values ('2012-02-28');
insert into example (date) values ('2012-02-29');
insert into example (date) values ('2012-03-01');
insert into example (date) values ('2012-03-02');
insert into example (date) values ('2012-03-03');
select date from example where julianday(date) - julianday('now') < 3 AND julianday(date) - julianday('now') > 0;
This would return (given that "today" is feb 28th) all the days that are one, two or three days in the future:
2012-02-29
2012-03-01
2012-03-02
Edit: To only return rows, regardless of year, you could do something like this - using a VIEW (again, exampl is directly in SQLite):
create view v_example as select _id, date,
strftime("%Y", 'now')||'-'||strftime("%m-%d", date) as v_date from example;
This VIEW would return the date & times in your database "rebased" on the current year - which, of course could introduce all manner of wonky behavior with leap years.
You can select all the dates like this in that case:
select date from v_example where
julianday(v_date) - julianday('now') < 3 AND
julianday(v_date) - julianday('now') > 0 ORDER BY v_date;
Which would return:
2012-02-29
2012-03-01
2001-03-01
2012-03-02
2010-03-02
If you want to sort by day and month consider storing the date as string in the format ddMMyyyy (you need two digits for day and month, otherwise the sorting will be flawed). Sorting by increasing values will give you dates sorted by day and month (and then year).
You can even do range query with string but you have to compute the query string.
Alternatively you may store the date as milliseconds in an additional column (this is the usual format for dates in the database) and do the range queries more easily with integer arithmetic.
One option is to use strftime() in SQLite to strip of the year and then do a comparison.
select * from sometable where strftime('%m-%d', somecolumn) = '02-28'
This will do a query of all rows for February 28th. But performance might be hurt if you have a large table and need to do a string conversion of every row for comparison. Maybe store the day and month in two additional columns if this query is performed often?