Skip to content
Advertisement

SQL JOIN to select MAX value among multiple user attempts returns two values when both attempts have the same value

Good morning, everyone!

I have a pretty simple SELECT/JOIN statement that gets some imported data from a placement test and returns the highest scored attempt a user made, the best score. Users can take this test multiple times, so we just use the best attempt. What if a user makes multiple attempts (say, takes it twice,) and receives the SAME score both times?

My current query ends up returning BOTH of those records, as they’re both equal, so MAX() returns both. There are no primary keys setup on this yet–the query I’m using below is the one I hope to add into an INSERT statement for another table, once I only get a SINGLE best attempt per User (StudentID), and set that StudentID as the key. So you see my problem…

I’ve tried a few DISTINCT or TOP statements in my query but either I’m putting them into the wrong part of the query or they still return two records for a user who had identically scored attempts. Any suggestions?

SELECT p.*
FROM
(SELECT 
    StudentID, MAX(PlacementResults) AS PlacementResults
    FROM AleksMathResults
    GROUP BY StudentID)
    AS mx
    JOIN AleksMathResults p ON mx.StudentID = p.StudentID AND mx.PlacementResults = p.PlacementResults
    ORDER BY
    StudentID

Advertisement

Answer

Sounds like you want row_number():

SELECT amr.*
FROM (SELECT amr.*
             ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY PlacementResults DESC) as seqnum
      FROM AleksMathResults amr
     ) amr
WHERE seqnum = 1;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement