Milan Batica
Milan Batica

Reputation: 21

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?

Upvotes: 1

Views: 526

Answers (2)

sagi
sagi

Reputation: 40491

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

Upvotes: 2

CompEng
CompEng

Reputation: 7416

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

Upvotes: 0

Related Questions