【问题标题】:Filter records in outer join based on criteria根据条件过滤外连接中的记录
【发布时间】:2021-10-15 19:06:01
【问题描述】:

我有 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 join filter oracle11gr2


【解决方案1】:

规范的SQL解决方案使用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;

【讨论】:

  • 其实我需要创建一个视图。我也可以试试这个查询吗?
  • @jaykio77 。 . .是的,只需将create view <viewname> as 放在select 之前。
  • 接受了您的回答。你能指导我吗?我知道简单的sql。但为了在讨论中创建查询,我应该阅读哪本书或在线参考资料
  • @jaykio77 。 . .我问错人了,因为我对自己的书有偏见。您可以在您最喜欢的在线书店进行调查。
猜你喜欢
  • 2015-11-01
  • 2011-07-26
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
相关资源
最近更新 更多