Oracle SQL:在子查询中具有orderby的Rownum抛出缺少的括号

时间:2019-02-20 01:27:49

标签: sql oracle subquery

我的sql如下所示。具有orderby子句的行将缺少括号。如何重写此查询以克服此错误?

update MY_TABLE1 a
    set (my_addr)=
    (select my_addr
        from MY_TABLE1 b
        where b.code1=a.code1
        and b.code2=a.code2
        and b.my_addr is not null
        and rownum = 1
        order by LAST_UPDTD_TMSTMP DESC)
    where a.my_addr is null
    and exists (select 1
        from MY_TABLE1 b
        where b.code1=a.code1
        and b.code2=a.code2
        and b.my_addr is not null)

如果我尝试再嵌套一个子查询,对别名'a'的引用就会消失。

update MY_TABLE1 a
    set (my_addr)=
    (select my_addr from (select my_addr
        from MY_TABLE1 b
        where b.code1=a.code1
        and b.code2=a.code2
        and b.my_addr is not null
        order by LAST_UPDTD_TMSTMP DESC) where rownum = 1)
    where a.my_addr is null
    and exists (select 1
        from MY_TABLE1 b
        where b.code1=a.code1
        and b.code2=a.code2
        and b.my_addr is not null)

非常感谢任何指针。

1 个答案:

答案 0 :(得分:1)

您可以使用keep来获取所需的值:

update MY_TABLE1 a
    set my_addr = (select max(my_addr) keep (dense_rank first order by LAST_UPDTD_TMSTMP DESC)
                   from MY_TABLE1 b
                   where b.code1 = a.code1 and
                         b.code2 = a.code2 and
                         b.my_addr is not null
                  )
    where a.my_addr is null and
          exists (select 1
                  from MY_TABLE1 b
                  where b.code1 = a.code1 and
                        b.code2 = a.code2 and
                        b.my_addr is not null
                 );