简体   繁体   中英

Oracle SQL:: Rownum with orderby in a subquery throws missing parenthesis

My sql looks like below. It is throwing missing parenthesis for the line having orderby clause. How can I rewrite this query to overcome this error?

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)

If I try to make one more nested subquery, the reference to alias 'a' disappears.

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)

Any pointers is much appreciated.

You can use keep to get the value that you want:

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
                 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM