I’m having difficulties creating a query to pull a certain result set from a MySQL database. The reason I’m stumbling around is possibly because I’m uncertain on how to ask the question. If there is something I have missed out, please leave a comment so that I can adjust the question to better reflect what I am trying to achieve.
What I have is 3 tables: results, answers and sections.
results has some data and has multiple answers.
each answer has a section_id.
To get all my answers and results I use the following query:
SELECT * FROM answers AS a
JOIN results AS r ON r.id = a.result_id
JOIN sections AS s ON s.id = r.section_id
How do I get the AVG of each section by result_id?
Example:
results:
id
1
2
answers:
id, result_id, sectionId, sum
1, 1, 1, 5
2, 1, 1, 8
3, 1, 2, 5
4, 1, 2, 7
5, 1, 2, 5
6, 2, 1, 5
7, 2, 1, 5
8, 2, 1, 8
9, 2, 2, 7
sections:
id, name
1, "test1"
2, "test2"
Expected results:
resultId, sectionId, avg
1, 1, 6.5
1, 2, 5.7
2, 1, 6
2, 2, 7
Just add a group by clause: