Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Latest Record 1

Status
Not open for further replies.

NotSQL

Technical User
May 17, 2005
205
GB
Hi,

I’m having problems getting the latest record/records from my table.

The scenario is: I have a currency table with the exchange rate based on a certain date. What i want to be able to do is select the distinct Currency code based on the max date, is this possible? Or is there a better way?

Table looks like this

CurrencyCode Date Rate
Dollar 01-03-2009 1.4
Dollar 03-04-2009 1.32
Dollar 04-05-2009 1.36
Krone 02-03-2009 10.34
Krone 06-04-2009 10.42
Krone 10-05-2009 9.43
Aus 21-03-2009 2.54
Aus 14-04-2009 2.11
Aus 06-05-2009 2.35

 
Would i use

Select max(date) currencyCode, Rate
From Table1
Group by CurrencyCode, Rate
 
NotSQL, that will work but it will give the wrong answer, i.e. it will give as many rows per currency as there are different rates for that currency

Code:
SELECT t.CurrencyCode
     , t.Date
     , t.Rate
  FROM ( SELECT CurrencyCode
              , MAX(Date) AS latest_date
           FROM Currencies
         GROUP
             BY CurrencyCode ) AS m
INNER
  JOIN Currencies AS t
    ON t.CurrencyCode = m.CurrencyCode
   AND t.Date = m.latest_date
:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Thanks R937, most appreciated

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top