selecting highest numbered object Oracle 12c

Jblue R
Jblue R used Ask the Experts™
on
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...
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2012
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.

Author

Commented:
Perfect.  Thank you !

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial