使用AVG 和GROUP BY 進行多個傳遞值的SQL 查詢
您在建立SQL 查詢以從資料中擷取特定資訊時遇到了困難具有以下結構的表:
+------------+--------------+----------------+ | id | pass | val | +------------+--------------+----------------+ | DA02959106 | 5.0000000000 | 44.4007000000 | | 08A5969201 | 1.0000000000 | 182.4100000000 | | 08A5969201 | 2.0000000000 | 138.7880000000 | ...
您的目標是產生一個提取以下資訊的查詢:
id, AVG of 'val' for 'pass' = 1, AVG of 'val' for 'pass' = 2, etc
所需的輸出應類似於:
+------------+---------+---------+---------+---------+---------+---------+---------+ | id | val_1 | val_2 | val_3 | val_4 | val_5 | val_6 | val_7 | +------------+---------+---------+---------+---------+---------+---------+---------+ | DA02959106 | 186.147 | 148.266 | 111.905 | 76.3985 | 44.4007 | 0 | 0 | +------------+---------+---------+---------+---------+---------+---------+---------+
解決方案1:直接方法
要實現此目的,您可以使用以下查詢:
SELECT id, pass, AVG(val) AS val_1 FROM data_r1 GROUP BY id, pass;
此查詢計算每個唯一組合的平均值id 和pass。
解決方案2:條件聚合
如果您希望每個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, ... from data_r1 d1 GROUP BY d1.id
此查詢使用條件聚合來計算每個id 內不同傳遞值的平均值。
以上是如何計算 SQL 查詢中不同傳遞值的平均值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!