tags:

views:

116

answers:

2

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)

A: 

Why don't you compare it with the $start date?

SELECT Date, Price
FROM table1
WHERE Date <= $end
AND Date >=$start

I've not tested it but it seems to work for me (if i've understood what you want to do)

mck89
That doesn't capture that I want the range to start /before/ the $start parameter if there is no date exactly on start. I will edit my original with some examples of expected behavior.
Johrn
+1  A: 

you don't need the "UNLESS there is no such date, in which case the start of the range should be the lowest date available" logic because if you simply select all dates after $start in the case of there not being a previous date, you automatically get the next latest date anyway. and you already know there are no records between $start and the next latest date, so don't bother trying to exclude them!

WHERE Date BETWEEN coalesce((select max(date)
                               from table1
                              where date <= $start)
                            , $start) and $end
longneck
testing this now, coalesce looks like it is definitely what I need.
Johrn
Worked like a dream once I stopped passing the dates in as integers >.< Thanks a million!
Johrn