简体   繁体   English

如何计算条件语句中按另一列分组的 mySQL 中的列的平均值?

[英]How to calculate the average of a column in mySQL grouped by another column in a conditional statement?

I need to calculate the average of one column where a second column has the same values.我需要计算第二列具有相同值的一列的平均值。 For example, you have例如,您有

Col1 | Col2
a    | 2
a    | 9
b    | 6
b    | 10

I need to retrieve the average of Col2 grouped by Col1, so (9+2)/2 and (6+10)/2.我需要检索按 Col1 分组的 Col2 的平均值,即 (9+2)/2 和 (6+10)/2。 I am able to retrieve it in its own separate query, but it's part of a condition where the average has to be greater than 7. The sample code in mySQL is我可以在自己的单独查询中检索它,但它是平均值必须大于 7 的条件的一部分。mySQL 中的示例代码是

SELECT Col1, AVG(Col2) FROM tableName
GROUP BY Col1;

SELECT Col1 FROM tableName
WHERE (SELECT AVG(Col2) GROUP BY Col1) >= 7;

The first query correctly gives me the average of Col2 grouped by Col1, but the second query simply takes the average of the entire Col2 and returns the values that are greater than the calculated average of all columns.第一个查询正确地给了我按 Col1 分组的 Col2 的平均值,但第二个查询只是取整个 Col2 的平均值并返回大于所有列的计算平均值的值。 Why is the second query not grouping by col1, and how should I change my code to correctly group the tuples?为什么第二个查询不按 col1 分组,我应该如何更改我的代码以正确分组元组?

You seem to want a having clause:你似乎想要一个having子句:

select col1, avg(col2) as avg_col2
from tablename
group by col1
having avg(col2) >= 7

MySQL supports column aliases in the having clause (this is an extension to the SQL standard), so you can simplify it as: MySQL 在having子句中支持列别名(这是对 SQL 标准的扩展),因此您可以将其简化为:

having avg_col2 >= 7

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

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