Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query for rows that have highest column value among rows that have same value for one of the columns

I have UserScores Table with data like this:

Id    userId   Score
1       1       10
2       2       5
3       1       5

I would like to have a query or SQL block that can give me the following output

Id    userId   Score
3       1       5
2       2       5

That is, I would like to pick rows that are unique by 'user id' that belonging to the highest 'id' column value.

like image 677
Krishna Kumar Avatar asked Feb 26 '23 12:02

Krishna Kumar


2 Answers

Another solution that would work on SQL Server 2000 (same as INNER JOIN above, but slightly faster) is:

SELECT id, userId, Score
  FROM UserScores
 WHERE id in (SELECT MAX(id)
                FROM UserScores
               GROUP BY userId
             ) 
 ORDER BY userId
like image 178
Niikola Avatar answered Mar 01 '23 05:03

Niikola


Use:

WITH summary AS (
    SELECT t.id,
                t.userid,
                t.score,
                ROW_NUMBER() OVER (PARTITION BY t.userid ORDER BY t.id DESC, t.score DESC) AS rank
        FROM USERSCORES sc)
SELECT s.id, 
            s.userid,
            s.score
    FROM summary s
 WHERE s.rank = 1
like image 29
OMG Ponies Avatar answered Mar 01 '23 03:03

OMG Ponies