selecting highest numbered object Oracle 12c

Need to select the slip with the largest number when grouped by stock from objects below:

create table tab1(horse number, stock number);
insert into tab1 values(100,4);
insert into tab1 values(101,5);

create table tab2(stock number, slip number);
insert into tab2 values(4, 1);
insert into tab2 values(4, 5);
insert into tab2 values(4, 8);
insert into tab2 values(5, 1);
insert into tab2 values(5, 5);
insert into tab2 values(5, 6);
insert into tab2 values(5, 7);
commit;

Open in new window

desired results
horse  stock  slip
 100       4        8
 101       5        7
 
 select t1.horse, t2.stock, t2.slip,
   rank ()
                   over (partition by horse, slip
                         order by slip desc)
                       rnk
  from tab1 t1
  join tab2 t2
  on t1.stock = t2.stock
  where rnk = 1

Open in new window

returns error:  "rnk" invalid identifier....

all pointers & suggestions appreciated...
Jblue RAsked:
Who is Participating?
 
sdstuberConnect With a Mentor Commented:
SELECT horse, stock, slip
    FROM (SELECT t1.horse,
                 t2.stock,
                 t2.slip,
                 RANK() OVER(PARTITION BY horse ORDER BY slip DESC) rnk
            FROM tab1 t1 JOIN tab2 t2 ON t1.stock = t2.stock)
   WHERE rnk = 1
ORDER BY horse


Since rnk is defined in the select, you need to wrap the whole query in parentheses to make an in-line view so you can reference rnk outside.

Also note I changed your PARTITION BY clause to remove slip from the partition clause.  With slip included then every row of horse/slip is unique so every row will have rank 1.
Since you want the rows for each horse ordered by slip, then slip is only in the order by.


You could use ROW_NUMBER or DENSE_RANK instead of RANK here also.
1
 
Jblue RAuthor Commented:
Perfect.  Thank you !
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.