gpt4 book ai didi

mysql - 使用 avg 和 group by 的 SQL 查询

转载 作者:IT老高 更新时间:2023-10-29 00:05:45 29 4
gpt4 key购买 nike

我在为 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'。

然后,我创建了 View 来表示“pass”=1、“pass”=2 等的每个查询的结果。但对于大多数 id,“pass”的最大值是 5。当使用 JOIN 查询获取 View 的最终结果我收到了一个空的结果集,因为一些 View 是空的/没有特定“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

关于mysql - 使用 avg 和 group by 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10702546/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com