简体   繁体   中英

Oracle, get top row using order by desc and rownum

This query gives me invalid identifier error, and i know it is because subquery will only be able to access data that is one layer higher.

select *
from   t2_callerid_plan cp
where  cp.subsrefnum in (
       select *
       from   (
              select vsap.subsrefnum
              from   prv_internet_responses_vsap vsap
              where  vsap.subsrefnum = cp.subsrefnum
              order by vsap.id desc
       )
       where rownum = 1
);

Now, i was wandering if there is way i can create query that would be able to return only the newest row while using the data from query in subquery?

You can use ROW_NUMBER() :

SELECT * FROM ( 
    SELECT cp.*,
           ROW_NUMBER() OVER(PARTITION BY cp.subsrefnum ORDER BY vsap.id desc) as rnk
    from t2_callerid_plan cp
    JOIN  prv_internet_responses_vsap vsap
     ON vsap.subsrefnum = cp.subsrefnum) p
WHERE p.rnk = 1

you can try this:

  select *
from   t2_callerid_plan cp
inner join
(
 select vsap.subsrefnum,ROW_NUMBER()  OVER (PARTITION BY subsrefnum ORDER BY vsap.id desc) rn
              from   prv_internet_responses_vsap vsap 
)vsap
on    vsap.subsrefnum = cp.subsrefnum and vsap.rn=1

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