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()
.