Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select Date that is closest to a date within a range

Status
Not open for further replies.

natrons

MIS
Apr 12, 2001
10
0
0
US
I am trying to find a solution to retrieve an individual record by selecting the date that is closest to a certain date but within a given range. The solution I've come up with is rather unwieldy and I wondered if anyone has suggestions on a more elegant solution.

For this example, I am trying to find record with the date that is closest to 2002-3-1, within a range of five days. I'm using Sybase SQLAnywhere :(. The table could have values that have the same date or dates before 2002-3-1 or dates after 2002-3-1. I want to find the record with the value closest to 2002-3-1.

Thanks for any insight, here is my SQL:

select lReadID, tReadDateTime
, nRange=5
, dtRangeStart = DATE('2002-3-1')
, CAST(ABS(tReadDateTime-dtRangeStart) as integer) as lDiffStart
, (SELECT MIN(ABS(R2.tReadDateTime-dtRangeStart)) FROM mReadings as R2 WHERE R2.lReadID=R.lReadID) as MinDiffStart
from mReadings as R
where
lDiffStart >= MinDiffStart AND tReadDateTime >= DATE(dtRangeStart-MinDiffStart)
ORDER BY
lReadID, tReadDateTime
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top