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 KEY
s and it just looks a bit ugly.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With