我在尝试从下表中计算累积组得分时遇到错误:
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
我正在努力实现这一目标:
Group Name Total Members Total Score (%)
==============================================
Group 1 2 75.00
----------------------------------------------
Group 2 2 50.00
----------------------------------------------
Group 3 1 0
----------------------------------------------
运行查询时,返回空结果。请在下面查看我的代码。
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;
答案 0 :(得分:1)
此查询将为您提供所需的结果。请注意,根据您问题中的表名,我已使用answers
作为答案表,如果它实际上称为answer
,则需要更改该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
输出:
name Total Members Total Score (%)
Group 1 2 75.00
Group 2 2 50.00
Group 3 1 0.00
答案 1 :(得分:0)
将“ LEFT JOIN答案a”更改为“ LEFT JOIN答案a”,它应该可以工作。
我还建议您避免使用别名,因为将临时表重命名为“ a”,“ g”之类的东西并没有任何好处,这对每个人来说确实很令人困惑,并且使调试/分析查询变得非常困难。另外,您应该使用MySQL客户端向您突出显示此类错误,例如MySQL Workbench或类似的内容。