Filter records in outer join based on criteria

23 views Asked by At

I have 2 simple tables as follows:-

 Student
 ---------------------------------------------
  student_id    student_name    student_class
     107           paul            A Level-I
     108           susan           Diploma
     109           jack            O Level-II 
 ---------------------------------------------

Student_Positions
--------------------------------------------------
 position_id      student_id    position    date
    1               107           1          1-1-2020
    2               107           1          1-1-2021
    3               109           2          1-1-2021
    4               109           1          1-6-2019
 

I want a left outer join on these tables for the latest position of every student as fol:-

 student_id    student_name     position       date
    107              paul          1          1-1-2021
    108             susan        
    109              jack          2          1-1-2021

I have made multiple tries with different positions of max(date) and group by but in vain. Please help with correct query

1

There are 1 answers

4
Gordon Linoff On BEST ANSWER

The canonical SQL solution uses a window function such as row_number():

select s.*, sp.position, sp.date
from students s left join
     (select sp.*,
             row_number() over (partition by student_id order by date desc) as seqnum
      from student_positions sp
     ) sp
     on sp.student_id = s.student_id and sp.seqnum = 1;