Skip to content
Advertisement

Calculate percentage of students SQL

How to calculate percentage of students with higher mark than average for each course?

Assume I have a table (avg_marks) with average marks for each course and number of students in the course:

I also have a table (enrolments) with all courses, students enrolled in those courses and their mark for the course:

The expected output would be the table with course id and percentage of students with higher marks than average:

I have calculated number of students who have higher mark than average, but somehow I wasn’t able to calculate the percentage (perhaps because the table contains all courses?). How can I modify this query or make a new one to calculate the percentage of students with higher mark than average?

Number of students with higher than average mark:

Output of the above query was like the following:

Advertisement

Answer

You don’t need the table avg_marks.
Use window function AVG() in enrolments to get the average mark for each course_id and then use conditional aggregation with AVG() aggregate function to get the percentage:

See the demo.

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