简体   繁体   中英

MySQL - calculate percentage of averages

I have the following table:

averages

id
subject_id
student_id
value
semester_id

classes_students

id
class_academic_year_id
student_id

classes_academic_years

id
class_id
academic_year_id

semesters

id
name
academic_year_id
start_date
end_date

I need a query to find out the graduation percentage of the students from a certain class for a certain subject of an academic year (ie the percentage of those whose average of averages is above 5; eg say student has average value 6 for semester_id = 1 and average value 7 for semester_id = 2, the average of averages will be 6.5).

Here is the current query, but it only returns the student_id and the average of averages for both semesters.

select averages.student_id, avg(value) from averages
inner join semesters on semesters.id = averages.semester_id
inner join academic_years on academic_years.id = semesters.academic_year_id

inner join classes_students on classes_students.student_id = averages.student_id
inner join classes_academic_years   on classes_academic_years.id = classes_students.class_academic_year_id

where averages.subject_id = '66' 
and academic_years.id = 3
and classes_academic_years.academic_year_id = academic_years.id
and classes_academic_years.class_id = 259

group by averages.student_id

I would like the result to be something like 74.5%. Is there a way to achieve this?

You should use that query and left join it by class.

SELECT COUNT(*) FROM classes_students GROUP BY class_academic_year_id ...

In this way you'll have COUNT(GRADUATED) / COUNT(*), that's a number between 0 and 1, so you just need to multiply it by 100 and you'll have your percentage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM