首页 >数据库 >mysql教程 >如何在 MySQL 中使用'AVG”和'GROUP BY”来计算表中不同组的列的多个平均值?

如何在 MySQL 中使用'AVG”和'GROUP BY”来计算表中不同组的列的多个平均值?

Susan Sarandon
Susan Sarandon原创
2024-10-27 11:56:02524浏览

How can you use  `AVG` and `GROUP BY` in MySQL to calculate multiple averages of a column for different groups within a table?

使用 AVG 和 Group By 的 SQL 查询

在 MySQL 中,提取表中不同组的列的多个平均值的查询可以可以使用 AVG() 和 GROUP BY 子句的组合来实现。考虑具有以下结构的表 data_r1:

mysql> select id, pass, val from data_r1 limit 10;
+------------+--------------+----------------+
| id         | pass         | val            |
+------------+--------------+----------------+
| DA02959106 | 5.0000000000 | 44.4007000000 |
| 08A5969201 | 1.0000000000 | 182.4100000000 |
| 08A5969201 | 2.0000000000 | 138.7880000000 |
| DA02882103 | 5.0000000000 | 44.7265000000 |
| DA02959106 | 1.0000000000 | 186.1470000000 |
| DA02959106 | 2.0000000000 | 148.2660000000 |
| DA02959106 | 3.0000000000 | 111.9050000000 |
| DA02959106 | 4.0000000000 | 76.1485000000 |
| DA02959106 | 5.0000000000 | 44.4007000000 |
| DA02959106 | 4.0000000000 | 76.6485000000 |

要从此表中提取所需信息,请使用以下查询:

SELECT id, pass, AVG(val) AS val
FROM data_r1
GROUP BY id, pass;

此查询对 data_r1 表中的行进行分组通过 id 和 pass 列,然后计算每组 val 列的平均值。结果是一张表,其中包含 id 和 pass 的每个唯一组合的一行,以及 val 的相应平均值。

另一种查询,它实现相同的结果,但为每个唯一 id 返回一行多个平均值:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 WHERE d2.id = d1.id AND pass = 7) as val_7
FROM data_r1 d1
GROUP BY d1.id

此查询使用嵌套子查询来计算特定 id 组内每个传递值的平均值。 IFNULL() 函数用于确保空值被 0 替换,防止除零错误。

以上是如何在 MySQL 中使用'AVG”和'GROUP BY”来计算表中不同组的列的多个平均值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn