【问题标题】:Select not groupable id on a group by query [duplicate]通过查询在组上选择不可分组的ID [重复]
【发布时间】:2020-08-26 19:48:28
【问题描述】:

我正在使用 Mysql 8.0 并尝试执行以下查询,但我没有达到预期的结果。我需要获取按公司分组的 max updated_at。

桌子:

id  | updated_at          | company
-----------------------------------
5   | 2011-04-14 01:06:06 | 1
3   | 2011-04-14 01:05:41 | 2
7   | 2011-04-15 01:14:14 | 2

查询:

select id, MAX(updated_at), company
from signatures
group by company

我遇到了一个错误,因为id 不能在一个组中。

有人可以帮我解决一下可以完成这项工作的查询吗?

提前致谢

【问题讨论】:

    标签: mysql group-by max


    【解决方案1】:

    使用窗口函数:

    select distinct
      first_value(id) over (partition by company order by updated_at desc) id,
      max(updated_at) over (partition by company) updated_at,
      company
    from signatures
    

    【讨论】:

    • 非常感谢!这个查询完成了工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2017-10-10
    • 2014-07-04
    相关资源
    最近更新 更多