Reputation: 77
I'm experiencing errors trying to calculate a cummulative group score from the table below:
group_details:
id name
=====================
1 Group 1
2 Group 2
3 Group 3
group_members:
id group_id
======================
1 1
2 1
3 2
4 2
5 3
answers:
id member_id is_correct
=================================
1 1 1
2 1 0
3 2 1
4 2 1
5 3 1
6 3 0
7 4 0
8 4 1
I am trying to achieve this:
Group Name Total Members Total Score (%)
==============================================
Group 1 2 75.00
----------------------------------------------
Group 2 2 50.00
----------------------------------------------
Group 3 1 0
----------------------------------------------
I get an empty result returned when I run the query. Kindly see my codes below.
SELECT
((SUM(a.is_correct) / (2 * SUM(m.id))) * 100) as cummulative_score,
SUM(m.id) as total_members,
g.name
FROM
`group_details` AS g
LEFT JOIN `group_members` m
ON m.group_id = g.id
LEFT JOIN `answers` a
ON a.member_id = m.id
WHERE a.is_correct = 1
GROUP BY g.id;
Upvotes: 1
Views: 60
Reputation: 780
Change "LEFT JOIN answer a" to "LEFT JOIN answers a" and it should work.
Also I recommend avoiding aliases because you don't do any good in renaming tables temporary into "a", "g" or something, it looks really confusing to everybody and it makes debugging/analyzing queries very hard. Also you should use a MySQL-client to highlight such errors to you like MySQL Workbench or something similar.
Upvotes: 0
Reputation: 147216
This query will give you the results that you want. Note that based on the table names in your question I have used answers
as the answer table, if it's actually called answer
you will need to change that JOIN
.
SELECT
g.name,
COUNT(DISTINCT m.id) AS `Total Members`,
ROUND(COALESCE(AVG(a.is_correct), 0) * 100, 2) AS `Total Score (%)`
FROM
`group_details` AS g
LEFT JOIN `group_members` m
ON m.group_id = g.id
LEFT JOIN `answers` a
ON a.member_id = m.id
GROUP BY g.id
Output:
name Total Members Total Score (%)
Group 1 2 75.00
Group 2 2 50.00
Group 3 1 0.00
Upvotes: 1