Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to get max value from each group [duplicate]

Tags:

sql

mysql

Say I have a table

Table Plays

date     | track_id  | user_id | rating
-----------------------------------------
20170416 | 1         | 1       | 3  (***)
20170417 | 1         | 1       | 5
20170418 | 2         | 1       | 1
20170419 | 3         | 1       | 4
20170419 | 3         | 1       | 2  (***)
20170420 | 1         | 2       | 5

What I want to do is for each unique track_id, user_id I want the highest rating row. I.e. produces this the table below where (***) rows are removed.

20170417 | 1         | 1       | 5
20170418 | 2         | 1       | 1
20170419 | 3         | 1       | 2
20170420 | 1         | 2       | 5

Any idea what a sensible SQL query is to do this?

like image 629
sradforth Avatar asked Sep 11 '26 16:09

sradforth


1 Answers

Use MAX built in function along with GROUP by clause :

    SELECT track_id, user_id, MAX(rating)
    FROM Your_table
    GROUP BY track_id, user_id;
like image 68
Mansoor Avatar answered Sep 13 '26 06:09

Mansoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!