您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

连接两个表,仅使用右表的最新值

连接两个表,仅使用右表的最新值

可以运行此命令的常规sql语句为:

select P.PartNum, M.Formula, M.RevisionNum
from Parts P
join Material M on P.PartNum = M.PartNum
where M.RevisionNum = (select max(M2.RevisionNum) from Material M2
                       where M2.PartNum = P.PartNum);

重复以上有关第26版修订之后的注意事项。max(RevisionNum)可能会中断,具体取决于#26之后发生的情况。

编辑:

如果RevisionNum序列总是从w / NEW开始,然后以A,B,C等继续,那么就需要用更复杂(又杂乱)的东西替换max():

select P.PartNum, M.RevisionNum
from Parts P
join Material M on P.PartNum = M.PartNum
where (
      (select count(*) from Material M2 
              where M2.PartNum = P.PartNum) > 1
      and M.RevisionNum = (select max(M3.RevisionNum) from Material M3
                   where M3.PartNum = P.PartNum and M3.RevisionNum <> 'NEW')
      )
      or ( 
      (select count(*) from Material M4
              where M4.PartNum = P.PartNum) = 1
       and M.RevisionNum = 'NEW'
      )

必须有更好的方法来做到这一点。尽管这行得通-必须考虑一个更快的解决方案。

sql小提琴:http://sqlfiddle.com/#!3/70c19/3

其他 2022/1/1 18:33:35 有286人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶