【问题标题】:How to solve "SELECT list is not in GROUP BY clause and contains nonaggregated column" without adding the column into "group by"?如何解决“SELECT 列表不在 GROUP BY 子句中并且包含非聚合列”而不将列添加到“group by”?
【发布时间】:2022-01-26 15:12:54
【问题描述】:

表:

id action project_id created_on last_updated_on
1 Update 123 2021.1.1 2021.5.3
2 creation 123 2021.1.4 2021.5.2
3 Update 123 2021.1.3 2021.5.1
4 Update 456 2021.2.1 2021.6.3
5 Update 456 2021.2.2 2021.6.2
6 creation 456 2021.2.3 2021.6.1

我想获取project 及其最近创建的Update 操作的last_updated_on 的地图。

我的说法是

select project_id, last_updated_on 
from table
where action = "Update"
group by project_id
order by created_on desc
limit 1

但是我得到了SELECT list is not in GROUP BY clause and contains nonaggregated column的错误。

我无法更改ONLY_FULL_GROUP_BY 属性。

在我的用例中,我认为我也不能将 last_updated_on 添加到 group by 中。

我也试过

select 
    project_id, 
    (select last_updated_on where created_on = max(created_on)) as "last_updated_on"
    .
    .
    .

但错误仍然发生。

希望有人可以帮助我。 提前问好!

更新:

示例表的期望结果:

project_id last_updated_on
123 2021.5.1
456 2021.6.2

解释:

  1. 对于project_id = 123,第1 行和第3 行的actionupdate
  2. order by created_on desc limit 1之后,第3行被选中,其last_updated_on2021.5.1

【问题讨论】:

  • 您想显示没有 UPDATE 操作的项目,还是直接忽略它们?

标签: mysql sql database


【解决方案1】:

你可以这样做:

select project_id, last_updated_on
from (
  select *, row_number() over(partition by project_id 
                              order by last_updated_on desc) as rn
  from t
  where action = 'Update'
) x
where rn = 1
order by created_on

将显示每个项目的最后更新操作。根本没有更新操作的项目将不会显示。

【讨论】:

  • 只是要去那里......但他们希望 Created by 列作为最终输出 ORDER
  • @DRapp 只需添加ORDER BY created_on
  • 他们可能希望输出中的 created_on 也跟随值是什么。我也会添加到您的专栏列表中。
  • @TheImpaler 非常感谢您的帮助。我相信这就是我需要的,但只有一个问题:order by last_updated_on desc 不应该是order by created_on desc 吗?因为我想获取update 的最近created 动作的last_updated_on 值。
  • @powerseed 看来您想通过行的关系进行过滤......我无法理解。我认为您可以通过在问题中添加确切的预期结果来澄清这一点。
猜你喜欢
  • 2016-04-27
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 2016-12-12
  • 2017-06-22
  • 2017-07-29
  • 2018-06-12
  • 1970-01-01
相关资源
最近更新 更多