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
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
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