473,836 Members | 2,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get the closest date

Hello,

I need help in writing a SQL statement in MS SQL Server 2000 to select
the latest date (i.e., the date closest to or equal to the current date)
for a given date.

For example, in a table I have the following records:
Date Exchange-Rate
01/Sep/03 0.55
05/Sep/03 0.59

If the given date is 02/Sep/03, then the rate 0.55 should be return.
If the given date is 03/Sep/03, then the rate 0.55 should be return.
If the given date is 04/Sep/03, then the rate 0.59 should be return.

Thanks in advanced,

Benny

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #1
8 39916
Benny Chow (be***@stg.net. nz) writes:
I need help in writing a SQL statement in MS SQL Server 2000 to select
the latest date (i.e., the date closest to or equal to the current date)
for a given date.

For example, in a table I have the following records:
Date Exchange-Rate
01/Sep/03 0.55
05/Sep/03 0.59

If the given date is 02/Sep/03, then the rate 0.55 should be return.
If the given date is 03/Sep/03, then the rate 0.55 should be return.
If the given date is 04/Sep/03, then the rate 0.59 should be return.


Next time, please include CREATE TABLE statements for the tables you
are working with and INSERT statements with sample data. This makes it
possible to post a tested solution.

Thus, this solution is untested:

SELECT exchangerage, date
FROM rates
WHERE date = (SELECT MAX(date)
FROM rates
WHERE date <= @date)

--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #2
CREATE TABLE ExchangeRates (rdate DATETIME PRIMARY KEY, exchangerate
DECIMAL(10,2) NOT NULL)
INSERT INTO ExchangeRates VALUES ('20030901',0.5 5)
INSERT INTO ExchangeRates VALUES ('20030905',0.5 9)

DECLARE @dt DATETIME
SET @dt = '20030902'

Here's one method:

SELECT exchangerate
FROM ExchangeRates
WHERE rdate =
(SELECT MIN(rdate)
FROM ExchangeRates
WHERE ABS(DATEDIFF(DA Y,@dt,rdate))=
(SELECT MIN(ABS(DATEDIF F(DAY,@dt,rdate )))
FROM ExchangeRates))

Or you can use TOP:

SELECT TOP 1 exchangerate
FROM ExchangeRates
ORDER BY ABS(DATEDIFF(DA Y,@dt,rdate)), rdate

Personally, I would avoid TOP because it's a MS proprietary extension to
SQL.

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #3
Benny wants the closest, before or after the specified date according to his
example.

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #4
Thanks David, this is exactly what I needed. :)

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #5
Benny,

This might be a little more efficient than other
solutions, but it's not as simple:

select top 1 exchangerate
from (
select exchangerate, pref
from (
select top 1 exchangerate, 1 as pref
from (
select top 3 rdate, exchangerate
from ExchangeRates E1
where E1.rdate >= (
select max(rdate) as lastBefore
from ExchangeRates E2
where E2.rdate < @dt
)
order by rdate
) X
order by case when rdate < @dt then @dt - rdate else rdate - @dt end
) X1
union all
select exchangerate, pref
from (
select top 1 exchangerate, 2 pref
from ExchangeRates
order by rdate
) Y
) T
order by pref

-- Steve Kass
-- Drew University
-- Ref: 250CBB08-57AE-45C7-97F2-AF26AFC368ED

Benny Chow wrote:
Hello,

I need help in writing a SQL statement in MS SQL Server 2000 to select
the latest date (i.e., the date closest to or equal to the current date)
for a given date.

For example, in a table I have the following records:
Date Exchange-Rate
01/Sep/03 0.55
05/Sep/03 0.59

If the given date is 02/Sep/03, then the rate 0.55 should be return.
If the given date is 03/Sep/03, then the rate 0.55 should be return.
If the given date is 04/Sep/03, then the rate 0.59 should be return.

Thanks in advanced,

Benny

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


Jul 20 '05 #6
David Portas (RE************ *************** *@acm.org) writes:
Benny wants the closest, before or after the specified date according to
his example.


Funny guy. :-) Some of our tables for prices and rates are sparse in a
similar manner, but we always assume that a value applies until a new
value comes in. So I assume he wanted the same.

But had Benny included CREATE TABLE and sample data in INSERT statements,
I would have seen that my solution was wrong!
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #7
> Funny guy. :-) Some of our tables for prices and rates are sparse in a
similar manner, but we always assume that a value applies until a new
value comes in. So I assume he wanted the same.
I agree that it seems like an unusual requirement. Although I suppose if you
wanted to calculate the value of a currency deal retrospectively it might
make sense to take the closest rate as the best approximation. But IANAA.

But had Benny included CREATE TABLE and sample data in INSERT statements,
I would have seen that my solution was wrong!


I know that feeling! :|

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #8
Thanks for all your guys help ^^.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
15934
by: Josh | last post by:
I need a query that will select the closest date. I have to tables Pricing and InventoryItem. tblInventoryItem InventoryItemID <- Pk Description tblPricing
1
5732
by: sk | last post by:
I have the following table CREATE TABLE Readings ( ReadingTime DATETIME NOT NULL DEFAULT(GETDATE()) PRIMARY KEY, Reading int NOT NULL ) INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050101', 1) INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050201', 12)
6
14404
by: KoRnDragon | last post by:
I know about getlastmod() but is there one for created date? If not is there some other way of getting the created date of a file?
2
1306
by: CK | last post by:
Good Morning, I have a view that contains rate information, contractIDs, and effective dates. I need to select the rate info based on contractID and date. I can provide a date and contractID, and I need to select the rate info for that contract where the effective date is <= dateprovided. I need the 1 record that is closest to that date. I am thinking something with max() perhaps. Any ideas? The <= effective
3
10263
by: randy1200 | last post by:
I have a DataView (dv) that includes a StartDate DateTime column. I'd like to return the DataView record that contains a StartDate value closest to my IncidentDate value: string filter = String.format("StartDate nearest {0}", IncidentDate); dv.Rowfilter = filter; Of course, there's no nearest function.
2
2766
by: josecruz | last post by:
I hope this make sense... When students leave school (dropout, medical reasons, etc), there is a date field that admission use to record this event. For program evaluation, I want to know what program (Electronics, Nursing, Drafting, etc) they were in or assigned at the time when they went on leave. My problem is that some times students switch programs several times and I only want the closest assignment program to the Leave date range. So...
1
4003
by: CatherineA | last post by:
I need help writing an SQL statement in Access 2007 to select the closest date/time. I have Spot Time (the date/time commercials ran) and Call Time (the date/time we received calls). I need to match these two fields so that I can tell which calls came in within 5 minutes before the Spot Time and which came in 15 minutes after. Between DateAdd("n",-5,) AND DateAdd("n",15,) This gives me results within that 20 minute time range, but does...
7
6565
by: GraemeC | last post by:
I have a form (single record form) that loads records from a query that are sorted date order as the records are viewed in date order. Some dates are in the past and some are in the future. Currently the form opens on the last record and the date of that record can be 6 months out. The users would like the form to open on the record closest to the current date. Does anyone know how I can achieve this? Thanks
10
6027
reginaldmerritt
by: reginaldmerritt | last post by:
I'm trying to open a form where the value of a field has a date closest to today but not beyond todays date. I guess i need some sort of MAX function in a where statment maybe???? Any ideas how i could do this. Thanks.
0
10527
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9358
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7774
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6975
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5812
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4443
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3102
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.