I need to find median of total scores region wise. I have got the solution after trial and error on data but the query is not in a optimized way. i need a efficient mysql query for this problem.
#Thanks for the solutions#
Edit: first exam
has to be filter from assessment
table and second total_score needs
to be summed for all subject of each student using studentassessment
table. Then finally region wise median needs to be calculated.
SELECT region,
Avg(total_score) AS median
FROM (SELECT row_num,
region,
total_score,
region_cnt
FROM (SELECT Row_number()
OVER (
partition BY region
ORDER BY total_score) AS row_num,
region,
total_score,
Count(region)
OVER (
partition BY region) AS region_cnt
FROM (SELECT i.region AS region,
Sum(S.score) AS total_score
FROM tredence.assesment A
INNER JOIN tredence.studentassessment S
ON A.id_assessment = S.id_assessment
INNER JOIN tredence.studentinfo i
ON i.id_student = S.id_student
WHERE A.assessment = 'Exam'
GROUP BY S.id_student,
i.region
ORDER BY region,
total_score) t) r
GROUP BY 1,
2,
3,
4
HAVING row_num IN ( Floor(region_cnt / 2), Ceil(region_cnt / 2) )) z
GROUP BY region
ORDER BY median DESC ```
tables and columns:
|Assessments |student_info|student_assessment|
|---------------|------------|------------------|
|course_code |course_code |id_assessment |
|batch_code |batch_code |id_student |
|id_assessments |id_student |date_submitted |
|assessment_type|gender |is_banked |
|date |region |score |
Output:
|Region |Median|
|-------------|------|
|North Region | 82 |
|London Region| 80 |
|Scotland | 80 |
|Ireland | 76 |