MySQL查询GROUP,COUNT

时间:2016-03-14 06:18:45

标签: mysql

我有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

我该如何解决?

1 个答案:

答案 0 :(得分: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_

https://msdn.microsoft.com/en-us/library/windows/desktop/dn457945(v=vs.85).aspx