根据条件过滤外连接中的记录

Filter records in outer join based on criteria

我有2个简单的表格如下:-

 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
 

我想在这些表上进行左外连接以获得每个学生的最新位置,如下所示:-

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

我多次尝试了 max(date) 和 group by 的不同位置,但都是徒劳的。 请帮助正确查询

规范的 SQL 解决方案使用 window 函数,例如 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;