Q
Problem solve Get help with specific problems with your technologies, process and projects.

Joining two tables but including the most recent row for each

I've got two tables, with a one-to-many relationship. The second table (the many) has foreign key to first table...

and a column with the effective date of that row. I want to join the tables but only include the most recent row (max(effective_date)) for each. Something like:

select * from table1 a,table2 b
where (a.key=b.key) and
  (b.key,b.effective_date in
     (select key,max(effective_date) as
           effective_date
        from table2
        group by key));

I'm using DB2. Thanks.


Pretty good try, but you cannot have more than one column involved in the IN (subquery) test, because the subquery is supposed to return what should essentially be a single list of values, not a multi-column result set.

A correlated subquery will do what you want --

select *
  from table1 a
     , table2 b
 where a.key=b.key
   and b.effective_date =
        (select max(effective_date)
           from table2
          where key = a.key)

For More Information


This was last published in May 2001

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close