Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value based on max of a different column grouped by another column [duplicate]

Tags:

sql

oracle

I want to get the values of a column based on max of a different column grouped by another column.

I have this table:

KEY NUM VAL
A   1   AB
B   1   CD
B   2   EF
C   2   GH
C   3   HI
D   1   JK
D   3   LM

And want this result:

KEY VAL
A   AB
B   EF
C   HI
D   LM

I could actually use this query to get it.

select KEY, VAL
from TABLE_NAME TN
where NUM = (
    select max(NUM)
    from TABLE_NAME TMP
    where TMP.KEY = TN.KEY
    )

However is there a more elegant way in ORACLE SQL (10g or above) to get the result?

Reason behind it is that there are actually multiple KEYs and it just looks a bit ugly.

like image 942
DRTauli Avatar asked Sep 15 '15 11:09

DRTauli


1 Answers

You can approach this using row_number():

select key, val
from (select t.*, row_number() over (partition by key order by num desc) as seqnum
      from table_name t
     ) t
where seqnum = 1;

Whether you consider this more "elegant" is probably a matter of taste.

I should point out that this is subtly different from your query. This is guaranteed to return one row for each key; yours could return multiple rows. If you want that behavior, just use rank() or dense_rank() instead of row_number().

like image 125
Gordon Linoff Avatar answered Nov 03 '22 10:11

Gordon Linoff