2

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?

sradforth
  • 2,176
  • 2
  • 23
  • 37

4 Answers4

6

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;
Mansoor
  • 4,061
  • 1
  • 17
  • 27
2

Assuming you want max date as well, try the following:

SELECT track_id, user_id, MAX(rating), MAX(date)
FROM plays
GROUP BY track_id, user_id;
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
2
select * from [table] t1
inner join
(
select track_id, user_id, max(rating) maxRating
from [table]
group by track_id, user_id
) tmp
on t1.track_id = tmp.track_id
and t1.user_id = tmp.user_id
and t1.rating = tmp.maxRating;
Biswabid
  • 1,378
  • 11
  • 26
2

If you have extra columns which is not mentioned in the GROUP BY clause you can go for a subquery like:

SELECT track_id,user_id,rating  --, other columns you want to display
FROM(
      SELECT track_id, user_id, rating,ROWNUMBER() OVER(PARTITION BY track_id, user_id ORDER BY rating DESC) as RN --,Other columns which you want to display
       FROM Your_table 
                        ) X
WHERE X.RN=1
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38