Search code examples
sqloracleselectgreatest-n-per-group

Need to retrieve all records in table A and only single one in table B that is the last updated


I have to retrieve certain records in TABLE_A - then need to display the last time the row was updated - which is in TABLE_B (however, there are many records that correlate in TABLE_B). TABLE_A's TABLE_A.PK is ID and links to TABLE_B through TABLE_B.LINK, where the schema would be:

TABLE_A
===================
ID          NUMBER
DESC        VARCHAR2

TABLE_B
===================
ID          NUMBER
LINK        NUMBER
LAST_DATE   DATE

And the actual table data would be:

TABLE_A
===================
100         DESCRIPTION0
101         DESCRIPTION1

TABLE_B
===================
1     100   12/12/2012
2     100   12/13/2012
3     100   12/14/2013
4     101   12/12/2012
5     101   12/13/2012
6     101   12/14/2013

So, I would need something to read out:

Result
====================
100   DESCRIPTION0    12/14/2013
101   DESCRIPTION1    12/14/2013

I tried to join different ways, but nothing seems to work:

select * from
(SELECT ID, DESC from TABLE_A WHERE ID >= 100) TBL_A
full outer join
(select LAST_DATE from TABLE_B WHERE ROWNUM = 1 order by LAST_DATE DESC) TBL_B
on TBL_A.ID = TBL_B.LINK;

Solution

  • The easiest thing to do would be to join table_a with an aggregate query on table_b:

    SELECT    table_a.*, table_b.last_date
    FROM      table_a
    LEFT JOIN (SELECT   link, MAX(last_date) AS last_date
               FROM     table_b
               GROUP BY link) table_b ON table_a.id = table_b.link