mysql - 错误 1140 (42000) 在没有 GROUP BY 的聚合查询中,表达式 #1

标签 mysql sql

我的问题来自https://www.hackerrank.com/challenges/earnings-of-employees/problem

下面是输入数据:

enter image description here

该问题要求找出最大收入(月数 * 薪水)和具有最大收入的行的总数。

我的尝试是:

select distinct salary*months, count(*)
from employee
where salary*months = (select max(salary*months) from employee)

这给了我错误信息:

ERROR 1140 (42000) at line 6: In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'run_byli4vf7yqz.employee.salary'; this is incompatible with sql_mode=only_full_group_by`

对我失败的原因有什么建议吗?

最佳答案

不要使用select distinct:

select (e.salary * e.months), count(*)
from employee e
where (e.salary * e.months) = (select max(e2.salary * e2.months)
                               from employee e2
                              )
group by (e.salary * e.months);

信息很清楚。你有 count(*) 所以你的查询是一个聚合查询。但是,您有一个未聚合的列,因此 MySQL 很困惑:您是否想要聚合?因此错误。

你也可以这样写:

select (e.salary * e.months), count(*)
from employee e
group by (e.salary * e.months)
order by (e.salary * e.months) desc
limit 1;

关于mysql - 错误 1140 (42000) 在没有 GROUP BY 的聚合查询中,表达式 #1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217148/

相关文章:

sql - 如何在查询中使用 FOR XML PATH ('' )而不转义特殊字符?

mysql - 用 MySQL 5.5.8 编写的存储过程在 5.1 中不起作用

c# - 不能向表中添加一个以上的用户。标识插入设置为关闭

php - 整数类型的 PDO 查询

mysql - 将整个表连接为单行

php - 如何从数据库中获取特定行?

C# - 无法更新 mysql 数据库列值

sql - Postgres 通过 ODBC 查询慢了一个数量级?

sql - "column not allowed here"INSERT语句错误

php - 从sql语句创建多个CSV文件