【问题标题】:ERROR 1140 (42000) In aggregated query without GROUP BY, expression #1错误 1140 (42000) 在没有 GROUP BY 的聚合查询中,表达式 #1
【发布时间】:2019-01-16 20:36:19
【问题描述】:

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

以下是输入数据:

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

我的尝试是:

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

这给了我错误信息:

第 6 行出现错误 1140 (42000):在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #1 包含非聚合列“run_byli4vf7yqz.employee.salary”;这与 sql_mode=only_full_group_by 不兼容`

有什么我失败的建议吗?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    不要使用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;
    

    【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2021-04-01
    • 2021-04-20
    • 1970-01-01
    • 2012-07-22
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多