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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL-Use most recent address

Status
Not open for further replies.

Mbroad

Programmer
Feb 26, 2004
49
US
Hello--I am writing SQL which utilizes several different tables to do a basic name and address extract. The name is one TABLEA and the Address is on TABLEB, however there are often multiple addresses for each name. there is a field on TABLEB which has the update date and time, so you would kmow the most recent address for that name.

I would like to know how I can select ONLY the most recent address for the name. The linking field in this case is called CASE #.
Your help is greatly appreciated.
MB

Government Coder Mark
 
I my opinion, you should use a subquery.

For example...

Code:
Select CaseNumber,
       Max(DateTimeColumn) As MaxDateTime
From   TableB
Group By CaseNumber

This will return the case number and the max date time.

Then, link back to the table to get the other fields, like so...

Code:
Select TableA.FieldList ...,
       TableB.FieldList ...
From   TableB
       Inner Join 
         (
         Select CaseNumber,
                Max(DateTimeColumn) As MaxDateTime
         From   TableB
         Group By CaseNumber
         ) As MaxDates
         On  TableB.CaseNumber = MaxDates.CaseNumber
         And TableB.DateTimeColumn = MaxDates.MaxDateTime
       Inner Join TableA
         On TableB.CaseNumber = TableA.CaseNumber

Hope this helps...

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Code:
SELECT Name, (SELECT TOP 1 TableB.Address FROM TableB WHERE TableB.FK = TableA.PK ORDER BY FieldThatIsUsed DESC) AS Address
FROM TableA

(not tested)

Borislav Borissov
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top