简体   繁体   English

MySQL 查询 GROUP、COUNT

[英]MySQL query GROUP, COUNT

I have problem with MySQL GROUP AND COUNT, they just don't work in the way I thought.我对 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

This is my MySQL query and error outputs.这是我的 MySQL 查询和错误输出。 Note that for group 1 avg_score should be ID1 avg_score 90 and ID2 avg_score 50, (90+50)/2=70请注意,对于组 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

How can I fix it?我该如何解决?

From your explanation, I can see that you want an average of averages.从您的解释中,我可以看出您想要平均值。 This can be solved with a derived table (nested select in FROM clause).这可以通过派生表(在FROM子句中嵌套选择)来解决。 Calculate the "inner" average first as such:首先计算“内部”平均值:

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

And then, nest that query as follows:然后,按如下方式嵌套该查询:

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 SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM