Reply to Re: Optimal search for the nearest date

Your name:

Reply:


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

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация