I have 2 tables, one which holds information about contracts and another which holds exchange rates.
The exchange rate table is made up of 3 fields
– two primary keys, one for the currency code (e.g. EURO) and one for the start date of the exchange rate
-One field which holds the exchange rate
The contract table just holds standard information about a contract along with the currency code as a foreign key to the exchange rate table and the date of the contract.
I’d like to be able to select each contract individually along with the applicable exchange rate for the date of the contract. So, for example, if my contract date is on the 20th of September 2012 and I have three exchange rates for the currency of that contract, one which starts on the 1st of September, one which starts on the 12th of September, and one that starts on the 30th September. How would I make sure that only the exchange rate for the 12th of September is returned along with the contract data and not any other rates, as the 20th of September falls within that ‘period’.
Would some sort of subquery be necessary?
I am using SQL Server 2005.
The problem with the data structure is that you have a first date but not a last date for the rates. One way to do this is with a correlated subquery. However, I prefer using the ranking function to assign the next date:
This is assigning the end date for the currency period in the fxrates CTE. For the most recent, the end date is tomorrow — presumably, all fxrates are in the past. It then joins to this table to get the appropriate rate for the contract.