views:

51

answers:

1

Ok SQL and Oracle gurus I have a somewhat complicated query that I'm trying to build.

Here is my current query:

select distinct person_info.person_name
     table2.value,
     table3.value,
     table4.value,
     table5.value
from person_info
    left join table2 on table2.person_name=person_info.person_name
    left join table3 on table3.person_name=person_info.person_name
    left join table4 on table4.person_name=person_info.person_name
    left join table5 on table5.person_name=person_info.person_name;

The primary key for every table is both the person_name and a timestamp. Now my problem is that if multiple instances of the same person_name exist in a table then I only want to left join on the most recent one. Does anyone know how to add this behavior to this query? I am using Oracle.

Thanks!

+4  A: 

Try:

select distinct person_info.person_name
     t2.value,
     t3.value,
     t4.value,
     t5.value
from person_info
    left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table2 t) t2 
         on t2.person_name=person_info.person_name and t2.rowno=1
    left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table3 t) t3
         on t3.person_name=person_info.person_name and t3.rowno=1
    left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table4 t) t4
         on t4.person_name=person_info.person_name and t4.rowno=1
    left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table5 t) t5
         on t5.person_name=person_info.person_name and t5.rowno=1;
Mark Bannister
What is the `product_id` for? After the `partition by` clause?
tkeE2036
Nevermind, I assume that it is supposed to be `person_name`. You might want to update your solution :) Thanks!
tkeE2036
Whoops! Well spotted - answer updated accordingly.
Mark Bannister