我在为MySQL编写SQL查询时遇到一些问题。我有一个具有以下结构的表:
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 |
我想创建一个查询,该查询从表中提取以下信息:
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 | +------------+---------+---------+---------+---------+---------+---------+---------+
当然,每个唯一的“ id”具有更多行。
我已经尝试过一些查询,例如
SELECT id, pass, AVG(val) AS val_1 FROM data_r1 WHERE pass = 1 GROUP BY id;
这将返回正确的结果,但是我必须使用“ pass”的其他可能值(最多7个)来扩展它
我尝试在AVG中使用嵌套的SELECT,但这没有用,因为我没有弄清楚如何正确地将其限制为当前的’id’。
然后,我创建了Views来表示每个查询的结果,其中“ pass” = 1,“ pass” = 2等。但是对于大多数id,“ pass”的最大值是5。当使用JOIN查询从中获取最终结果时这些视图收到的结果集为空,因为某些视图为空/没有特定“ id”的值。
有任何想法吗?
如果我了解您的需求,请尝试以下操作:
SELECT id, pass, AVG(val) AS val_1 FROM data_r1 GROUP BY id, pass;
或者,如果每个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