Table structure-
int PrimaryKey
DateTime Date
int Price
What I would like to do is pass in a start and end date, and get the range
From:
The greatest date that is less than or equal to start UNLESS there is no such date, in which case the start of the range should be the lowest date available.
To:
The end date.
My query so far is:
SELECT Date, Price
FROM table1
WHERE Date <= $end
AND Date >=
(
SELECT Date
FROM table1
WHERE Date <= $start
ORDER BY Date DESC
LIMIT 1
)
The subquery gets the largest date that is less than or equal to the start value, which is then used as the low end of the range for the main query. Any suggestions for getting the 'UNLESS' clause in there?
For example, given a table with dates:
Jan 1, 2009
Feb 1, 2009
Mar 1, 2009
Apr 1, 2009
I want a query with $start='Feb 18, 2009'
and $end='Apr 30, 2009'
to return the three rows Feb 1, Mar 1, Apr 1 (Feb 1, 2009 is the largest date that is less than or equal to $start).
But if I provide $start='Dec 1, 2009'
and $end='Apr 30, 2009'
I want all four rows returned (There is no date that is less than or equal to $start, so the range starts at the lowest date)