帅哥们好!
我这里是Oracle数据库环境,有两张表
表A(id,status),主键(id)
表B(id,eid,status),主键(id,eid),其中id还是外键表A的数据
  id status
---- ------
   1      0
   2      0
   3      0
   4      1
   5      1表B的数据
  id eid status
---- --- ------
   1   1      0
   1   2      0
   1   3      0
   2   1      0
   2   2      0
   3   1      0
   4   1      0
   4   2      0
   4   3      0
   5   1      0
   5   2      0把B表中id相同的记录看作一组,现在要把每组中eid最大的记录的status列改得和A表的status相同,该如何写sql语句?
本例中应该把B表最后一行和倒数第3行的status改为1。
我想了一整天,也不知道该如何写这个update语句,哪位大侠帮帮忙啊,不胜感激

解决方案 »

  1.   

    OPER@tl> select * from test;        ID     STATUS
    ---------- ----------
             1          0
             2          0
             3          0
             4          1
             5          1OPER@tl> select * from test2;        ID        EID     STATUS
    ---------- ---------- ----------
             1          1          0
             1          2          0
             1          3          0
             2          1          0
             2          2          0
             3          1          0
             4          1          0
             4          2          0
             4          3          0
             5          1          0
             5          2          0已选择11行。OPER@tl> update test2 a
      2  set status=(select status from test b
      3  where a.id=b.id)
      4  where rowid in(select rowid
      5  from (select rowid,row_number() over(partition by id order by eid desc)
      6  from test2)
      7  where rn=1);已更新5行。OPER@tl> select * from test2;        ID        EID     STATUS
    ---------- ---------- ----------
             1          1          0
             1          2          0
             1          3          0
             2          1          0
             2          2          0
             3          1          0
             4          1          0
             4          2          0
             4          3          1
             5          1          0
             5          2          1已选择11行。OPER@tl>
      

  2.   

    最后那个第7行那个rn好像没有出现过,是不是应该加在“order by eid desc)”后面,不管怎样,意思是懂了,thx vc555
      

  3.   

    自己又发现一种不使用分析函数的简单方法
    update b set status=(select status from a where a.id=b.id)
    where (id,eid)in 
    (
    select id,max(eid)from b
    group by id
    )
    以前怎么没想到子查询里还可以返回多列喃?