I have an ExchangeRates table that has a countryid and an exchanger, something with this:
ExchangeRateID Country ToUSD ExchangeRateDate 1 Euro .7400 2/14/2011 2 JAP 80.1900 2/14/2011 3 Euro .7700 7/20/2011
Please note that there may be one and the same country with a different rate based on the date ... for example, the Euro was above .7400 on 2/14/2011 and now is .7700 on 7/20/2011.
I have another position table for listing items based on country. In this table, each item has a date associated with it. The position date should use the appropriate date and country based on the exchange rate. Therefore, using the above data, if I had a position with the euro of the country on 2/16/2011, it should use the euro value for 2/14/2011, and not the value for 7/20/2011 because of the date (condition er. ExchangeRateDate <= erli.LineItemDate). This will work if I only have one item in the table, but imagine that I had position date 8/1/2011, then this condition (er.ExchangeRateDate <= erliLineItemDate) will return several rows, therefore my query will fail. .
SELECT er.ExchangeRateID, er.CountryID AS Expr1, er.ExchangeRateDate, er.ToUSD, erli.ExpenseReportLineItemID, erli.ExpenseReportID, erli.LineItemDate FROM dbo.ExpenseReportLineItem AS erli LEFT JOIN dbo.ExchangeRate AS er ON er.CountryID = erli.CountryID AND DATEADD(d, DATEDIFF(d, 0, er.ExchangeRateDate), 0) <= DATEADD(d, DATEDIFF(d, 0, erli.LineItemDate), 0) WHERE (erli.ExpenseReportID = 196)
The problem with this left join ... is that the dates are <= the position date, so it returns a lot of records, I need to do it somehow, but I don't know how to do it.
LineItem tables have multiple records, and each record can have its own CountryID:
Item Country ParentID LineItemDate Line Item 1 Euro 1 2/14/2011 Line Item 2 US 1 2/14/2011 Line Item3 Euro 1 2/15/2011
So, there are three entries for ParentID (ExpenseReportID) = 1. So, I take these entries and join the ExchangeRate table, where the Country in my position table = country of the exchange rate table (this part is simple) BUT the second condition I need to make is this is:
AND DATEADD(d, DATEDIFF(d, 0, er.ExchangeRateDate), 0) <= DATEADD(d, DATEDIFF(d, 0, erli.LineItemDate), 0)
But the problem here is that it will return a few lines from my exchange rate table, because the euro is displayed twice.