I have seen the answer from a previous post, which works fine but I have a small dilemma. Taking the same scenario:
A table that list students' grades per class. I want a result set that looks like:
BIO...B
CHEM...C
Where the "B" and "C" are the modes for the class and want to get the mode for the class.
Once I applied the below query, i got the following output:
Class | Score | Freq | Ranking
2010 | B | 8 | 1
2010 | C | 8 | 1
2011 | A | 10 | 1
2012 | B | 11 | 1
In 2010, I have two grades with the same frequency. What if..I just want to display the highest score, in this case will be "B". How can I achieve that? I would need to assign rankings to the letter grades, but I'm not sure how. Please advise. Thanks.
Prior post: SQL Server mode SQL
The query I used to retrieve the data was the answer from Peter:
;WITH Ranked AS (
SELECT
ClassName, Grade
, GradeFreq = COUNT(*)
, Ranking = DENSE_RANK() OVER (PARTITION BY ClassName ORDER BY COUNT(*) DESC)
FROM Scores
GROUP BY ClassName, Grade
)
SELECT * FROM Ranked WHERE Ranking = 1
Change:
SELECT * FROM Ranked WHERE Ranking = 1
To:
SELECT Class, MIN(Grade) AS HighestGrade, Freq, Ranking
FROM Ranked
WHERE Ranking = 1
GROUP BY Class, Freq, Ranking