|
Posted by Erland Sommarskog on 11/17/05 01:26
sk (shripathikamath@hotmail.com) writes:
> It is a table of readings of a free-running counter that is
> time-stamped. I need to determine the value of the reading that
> corresponds to the closest date to the supplied date
>
> Are there more optimal/efficient ways of accomplishing this than the
> following?
>
> DECLARE @when DATETIME
> SET @when = '20050505'
>
> SELECT TOP 1 ReadingTime, Reading FROM Readings
> ORDER BY abs(DATEDIFF(minute, ReadingTime, @when))
>
> The above gives me the desired result of ('20050401', 31).
This might be better:
SELECT R.ReadingTime, R.Reading
FROM Readings R
JOIN (SELECT TOP 1 ReadingTime
FROM (SELECT ReadingTime = MAX(ReadingTime)
FROM Readings
WHERE ReadingTime < @when
UNION
SELECT ReadingTime = MIN(ReadingTime)
FROM Readings
WHERE ReadingTime > @when) AS a
ORDER BY abs(DATEDIFF(minute, ReadingTime, @when))) AS R2
ON R.ReadingTime = R2.ReadingTime
While more complex, it may perform better, but you will have to
benchmark.
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
Navigation:
[Reply to this message]
|