使用 AVG 和 GROUP BY 的 SQL 查询:提取每个字段的平均值
您寻求一个从表中提取特定信息的 SQL 查询,即每个唯一“id”和“pass”值的“val”字段的平均值。
要实现此目的,您可以使用简单但高效的查询:
<code class="sql">SELECT id, pass, AVG(val) AS val_1 FROM data_r1 GROUP BY id, pass;</code>
此查询按“id”和“pass”对数据进行分组,计算每个组合的“val”的平均值。生成的表包含一行,用于表示每对唯一的“id”和“pass”值。
或者,如果您希望每个唯一的“id”使用一行,并包含所有“pass”值的平均值,使用此查询:
<code class="sql">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</code>
此查询对每个“pass”值使用嵌套子查询来计算平均值。然后,它按“id”聚合结果,提供数据的综合视图。
以上是如何使用 SQL 计算其他两个字段的每个唯一组合的字段平均值?的详细内容。更多信息请关注PHP中文网其他相关文章!