mysql连接3个表并计算累计百分比

nwo49xxi  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(328)

我在尝试从下表计算累积组分数时遇到错误:

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;
gajydyqb

gajydyqb1#

将“left join answers a”更改为“left join answers a”,它应该可以工作。
另外,我还建议避免使用别名,因为将临时表重命名为“a”、“g”或其他什么都做不到,这会让每个人都感到困惑,并且会使调试/分析查询变得非常困难。此外,还应该使用mysql客户机向mysql workbench或类似的工具突出显示这些错误。

vd2z7a6w

vd2z7a6w2#

此查询将为您提供所需的结果。请注意,根据您问题中的表名,我使用了 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

相关问题