Skip to content
Advertisement

MySQL Query with distinct on a column value

I have this table (with 100k+ rows):

I want to get for each emote_id the row where count is the highest for this emote_id

So for this example I’d like to get this as response:

I’m stuck at building the query and need help. 🙁

Advertisement

Answer

You can use nested subquery with max() aggregation

for db version 8+ you can use window analytic functions such as dense_rank():

Demo

All matching maximum values for count return through use of dense_rank() in case of tie( having equal valued count for any of emote_id ). If analytic function was row_number(), then only one row would return even if tie occurs.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement