SQL Server mode SQL
sql, t-sql
Solution
here, something like this on SQL 2005/2008:
;WITH
Counts AS (
SELECT ClassName, Grade, COUNT(*) AS GradeFreq
FROM Scores
GROUP BY ClassName, Grade
)
, Ranked AS (
SELECT ClassName, Grade, GradeFreq
, Ranking = DENSE_RANK() OVER (PARTITION BY ClassName ORDER BY GradeFreq DESC)
FROM Counts
)
SELECT * FROM Ranked WHERE Ranking = 1
or perhaps just:
;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
Problem
I have 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. I can get a mode of all of the grades, but not sure how to get the mode per class