获得嵌套SQL查询中一列的平均值

时间:2014-09-18 22:32:08

标签: mysql sql sql-server

为了简单起见,我会尽量简化这一过程。我需要获取查询返回列的平均值。合理?我会试着详细说明。(从另一个问题借来的样本结果)

Plant_ID | Year |Quarter| MR  | Range
| CCAR   | 2009 | 1     | 706 | Null
| CCAR   | 2009 | 2     | 626 | 0,08
| CCAR   | 2009 | 2     | 637 | 0,11
| CCAR   | 2009 | 2     | 737 | 0,1
| CCAR   | 2009 | 1     | 552 | 0,19
| CCAR   | 2009 | 4     | 418 | 0,137
| CCAR   | 2009 | 1     | 503 | 0,085
| CCAR   | 2009 | 2     | 645 | 0,058
| CCAR   | 2009 | 4     | 743 | 0,098
| CCAR   | 2009 | 3     | 556 | 0,187
| CCAR   | 2009 | 1     | 298 | 0,258
| CCAR   | 2009 | 2     | 339 | 0,041
| CCAR   | 2010 | 1     | 381 | 0,042

当我运行像这样的查询

时,我会得到这个结果
Select PlantID, Year, Quarter, MR, Range FROM TestTable WHERE PlantID in('CCAR')

我想要每个季度的平均MR。初步我会尝试这样的事情。

Select Quarter, AVG(MR) FROM (Select PlantID, Year, Quarter, MR, Range FROM TestTable WHERE PlantID in ('CCAR')) GROUP BY Quarter ORDER BY Quarter

问题是我不知道在哪里嵌套查询来完成此任务。有什么帮助吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

添加别名,例如你好

Select Quarter, AVG(MR) FROM 
(Select PlantID, Year, Quarter, MR, Range FROM TestTable WHERE PlantID in ('CCAR')) hallo    
GROUP BY Quarter ORDER BY Quarter

虽然在这种情况下不需要,但以下就足够了

Select Quarter, AVG(MR)
FROM TestTable 
WHERE PlantID in ('CCAR')   
GROUP BY Quarter 
ORDER BY Quarter   

答案 1 :(得分:0)

只需使用聚合:

select Year, Quarter, avg(MR)
from TestTable
where PlantID in ('CCAR')
group by Year, Quarter;

我认为你想要这一季度的季度。如果没有,只需从selectgroup by删除年份。