I'm using a SQL Server database.
Given the following query, I'm trying to get the highest score for each class. The Scores
table has 50 rows for two classes so I want a total of 2 rows. But, because I have the Scores.Id
, it returns each row for the Scores
since Scores.Id
is unique. Of course the simple solution is to remove the Scores.Id
column except I need to know the Scores.Id
to do additional lookup.
SELECT
Class_Id, Scores.Id, MAX(Scores.ClassScore) AS Score
FROM
Classes
INNER JOIN
Scores ON Classes.Id = Scores.Class_Id
GROUP BY
Scores.Class_Id, Scores.Id
Is this what you want?
Given the information that you want, the join to
Classes
is superfluous.The max score by class_id is simply
If you then need to know which rows in the scores table had the max score you can do a join. You may get more than two rows if there's more than one equal max score per class.
Or I might use a cte
This looks like a job for the
rank
window function: