【问题标题】:How do I get the AVG of multiple GROUPs, by the Parent's table ID in MySQL如何通过 MySQL 中的父表 ID 获得多个组的平均值
【发布时间】:2012-03-12 13:02:20
【问题描述】:

我在创建查询以从 MySQL 数据库中提取某个结果集时遇到困难。我跌跌撞撞的原因可能是因为我不确定如何提出这个问题。如果我遗漏了什么,请发表评论,以便我可以调整问题以更好地反映我想要实现的目标。

我有 3 个表格:结果、答案和部分。

results 有一些数据并且有多个答案。

每个答案都有一个 section_id。

为了获得我所有的答案和结果,我使用以下查询:

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

如何通过result_id得到每个section的AVG?

例子:

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"

预期结果:

resultId, sectionId, avg
1, 1, 6.5
1, 2, 5.7
2, 1, 6
2, 2, 7

【问题讨论】:

  • 我试图获得一个取决于 result_id 和 section_id 的平均值。目前它添加了所有 result_id 的总和。我还需要这个来为 section_id 提供服务吗?

标签: mysql group-by average


【解决方案1】:

试试这个:

SELECT a.id, b.sectionID, avg(`sum`) TotalAverage
FROM results a INNER JOIN answers b on a.id = b.resultID
    INNER JOIN sections c on b.sectionID = c.id
GROUP BY a.id, b.sectionID

PS:您应该在表answers 的列SUM 中添加一个反引号,因为SUMRESERVED WORD in MySQL

【讨论】:

    【解决方案2】:

    只需添加一个 group by 子句:

    SELECT r.result_id, s.section_id, avg(sum)
    FROM answers AS a
    JOIN results AS r ON r.id = a.result_id
    JOIN sections AS s ON s.id = r.section_id
    GROUP BY r.result_id, s.section_id
    

    【讨论】:

      【解决方案3】:
      SELECT result_id, sectionId, AVG(`sum`) AS `avg` FROM answers GROUP BY result_id, sectionId;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-13
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多