使用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中文網其他相關文章!