I am working with SQLite.
Suppose I have a table sales
with two columns, date
and count
, to keep track of how many glasses of lemo
I think you need something like this:
SELECT sum(count) / ((strftime('%s','2010-01-10')-strftime('%s','2010-01-04')+86400)/86400)
FROM sales
WHERE date IS BETWEEN '2010-01-04' AND '2010-01-10';
The query calculates the exact number of days by taking the seconds between the given dates
and dividing with 86400 (= 24*3600) secs.
For example
SELECT (strftime('%s','2010-03-01')-strftime('%s','2010-01-01') + 86400) / 86400
outputs 60
which is the correct value.
Check out SQLite's Date And Time Functions.
Create a calendar table and join onto that:
Something like this will do:
create table dates (id integer primary key);
insert into dates default values;
insert into dates default values;
insert into dates select null from dates d1, dates d2, dates d3 , dates d4;
insert into dates select null from dates d1, dates d2, dates d3 , dates d4;
alter table dates add date datetime;
update dates set date=date('2000-01-01',(-1+id)||' day');
That will cover you till 2287-05-20 Adding an index to the date column in the dates table won't hurt. My sqlite is little rusty, so I suggest you consult the manual on that.
Edit: Code for the index:
create unique index ux_dates_date on dates (date);
You could use a Recursive Common Table expression to generate a series of dates and join to it:
WITH RECURSIVE
cnt(x) AS (
SELECT 0
UNION ALL
SELECT x+1 FROM cnt
LIMIT (SELECT ((julianday('2010-01-10') - julianday('2010-01-04'))) + 1)
),
WITH date_series AS (
SELECT date(julianday('2010-01-04'), '+' || x || ' days') as date
FROM date_series ds
)
SELECT AVG(COALESCE(s.count, 0)) as avg_sales_count
FROM date_series ds
LEFT JOIN sales s ON ds.date = s.date
I wrote a blog post with more info here: http://www.geekytidbits.com/generate-date-range-sqlite/