If you want to improve your chances of getting help, you really should post the DDL statements to create your tables and the DML statements to insert sample data into your tables. It's usually a good idea to use table variables for doing this so that people don't have to drop the tables afterward.
DECLARE @Currencies TABLE (
, CurrencyCode char(3)
, CurrencyDesc varchar(50)
SELECT 1,'USD','USA Dollar'
SELECT 2,'EUR','European Euro'
SELECT 3,'Yen','Japan Yen'
DECLARE @ExchangeRate TABLE (
, Equivalent float
, ExchangeRateDate datetime
You also might want to avoid using keywords (like KEY or DATETIME) as column or table names. If you forgot to correctly delimit them, you could get SQL errors.
I would use a CTE and the Row_Number() function to solve your problem. Since you want the most recent for each currency
, you need to use the PARTITION BY
clause, and since you want the most recent, you need to sort your ORDER BY clause in DESC
order. The WHERE clause in the final select gives you the most recent exchange rate.
WITH OrderedExchangeRates AS (
SELECT CurrencyID, Equivalent, ExchangeRateDate
-- The following is the key to getting the latest rate.
, ROW_NUMBER() OVER( PARTITION BY CurrencyID ORDER BY ExchangeRateDate DESC ) AS RowNum
SELECT c.CurrencyID, c.CurrencyCode, c.CurrencyDesc, er.Equivalent, er.ExchangeRateDate
FROM @Currencies AS c
INNER JOIN OrderedExchangeRates AS er
ON c.CurrencyID = er.CurrencyID
WHERE er.RowNum = 1
J. Drew Allen
Business Intelligence Analyst
How to post data/code on a forum to get the best help.How to Post Performance Problems
Make sure that you include code in the appropriate IFCode tags, e.g. [code=sql]<your code here>[/code]. You can find the IFCode tags under the INSERT
options when you are writing a post.