gpt4 book ai didi

MySQL 查询 GROUP, COUNT

转载 作者:行者123 更新时间:2023-11-28 23:35:10 24 4
gpt4 key购买 nike

我对 MySQL GROUP AND COUNT 有疑问,它们并不像我想的那样工作。

Table1
ID | group_
1 1
2 1
3 2

Table2
ID | score
1 100
1 80
2 50
3 50

OUTPUT
group_ | group_avg_score | group_num
1 70 2
2 50 1

这是我的 MySQL 查询和错误输出。请注意,对于组 1 avg_score 应该是 ID1 avg_score 90 和 ID2 avg_score 50,(90+50)/2=70

SELECT  A.group_, ROUND(AVG(B.score),2) as group_avg_score, COUNT(*) as group_num
FROM Table1 A, Table2 B
WHERE A.ID=B.ID
GROUP BY group_

OUTPUT
group_ | group_avg_score | group_num
1 76.67 3
2 50 1

我该如何解决?

最佳答案

从您的解释中,我可以看出您想要平均值的平均值。这可以通过派生表来解决(FROM 子句中的嵌套选择)。首先计算“内部”平均值:

SELECT ID, AVG(score) AS score
FROM Table2
GROUP BY ID

然后,按如下方式嵌套该查询:

SELECT Table1.group_, AVG(Table2.score) AS group_avg_score, COUNT(*) AS group_num
FROM Table1
JOIN (
SELECT ID, AVG(score) AS score
FROM Table2
GROUP BY ID
) Table2
ON Table1.ID = Table2.ID
GROUP BY Table1.group_

SQLFiddle

关于MySQL 查询 GROUP, COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980721/

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