Skip to content
Advertisement

Count number of students above and below the average score in SQL

I have a sample table below and I am trying to get the number of student above the average score and number of students below the average score.

The target result table is supposed to look like

I have been able to write a query to get the names of students above the average score and this can be easily edited to get the count of students below the avg score.

The issue here is that I want to add the counts in a table indicating the number of students above and below the average score.

If a number is equal to the average score, it can be considered as above the average score.

Advertisement

Answer

If you are running MySQL 8.0, you can use window functions and aggregation:

In earlier versions, you can join the table with an aggregate query that computes the average score per subject:


Edit: you appear to be running Big Query, not MySQL as initially tagged. You can use COUNTIF():

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement