I've got this SQL QUERY in MS SQL 2005/2008 database which gets me Money Amount, Money Currency, Money Time and Currency Converter. I left join it with Table that has gathered information from polish national bank about currency converter per each day.
Here's the query:
SELECT t1.[TransakcjeGotowkoweKwota],
t1.TypyWaluty,
t1.[TransakcjeGotowkoweData],
t2.[kurs_sredni]
FROM [BazaZarzadzanie].[dbo].[TransakcjeGotowkowe] t1
LEFT JOIN [BazaZarzadzanie].[dbo].[KursyWalutNBP] t2
ON t1.TypyWaluty = t2.[kod waluty] AND t2.[data publikacji] = t1.[TransakcjeGotowkoweData]
WHERE [TypyWaluty] = 'EUR'
Here's the output:
TransakcjeGotowkoweKwota TypyWaluty TransakcjeGotowkoweData kurs_sredni
-14153.04000000 EUR 2009-01-05 00:00:00.000 4,1137
-18.36000000 EUR 2009-07-01 00:00:00.000 4,4157
4.61000000 EUR 2007-09-30 00:00:00.000 NULL
55.50000000 EUR 2007-09-30 00:00:00.000 NULL
The problem is with NULL values for Kurs_sredni. It happens when [kurs_sredni] cannot be found in [KursyWalutNBP] for that particular day. What i would like to achieve is when it happens it should get the nearest possible date and get value for that day.
For example:
If value is NULL for [Kurs Sredni] for date 2007-09-30 it should get value from 2007-10-01 (if it has one of course).
How should i aproach this?
With regards,
MadBoy
Best Answer
I would personally move to a User Defined Function for this type of thing, rather than a join. This way you can have full control over the evaluation process. You could do it in a manner like the following, based on your notes.
This way, you can do a >= comparison on date, and if it doesn't exist, you will get the next latest date value.