Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mode in SQL

Tags:

sql

mode

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
like image 527
Frida Avatar asked Nov 07 '12 21:11

Frida


People also ask

How do you calculate mode in SQL?

To calculate the Mode, first we have to count the occurrences of each unique salaries in the salary column. Next, we will have to use the DENSE_RANK window function to rank these counts of the salaries. And once we have these ranking all we need to do is use a subquery and select the rows where rnk = 1.

Is there a mode in SQL?

The MODE function returns the mode (the most frequently occurring value) of a numeric expression. When there are no duplicate values in the data, then MODE returns NA . The numeric expression whose mode is to be calculated. The dimensions of the result.

How do you calculate mean median and mode in SQL?

Median is calculated by ordering all the data points from the series in ascending order and then picking out the middle data point from it. If there are two middle data points, then the median will be calculated as the mean of those two numbers.

How do you calculate mode in Oracle SQL?

How Can I Calculate the Mode in Oracle SQL? To calculate the mode, we need to use the STATS_MODE function. The mode is 12 as that is the most occurring value in the table.


1 Answers

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
like image 50
D'Arcy Rittich Avatar answered Sep 24 '22 06:09

D'Arcy Rittich