【问题标题】:SQL must appear in the GROUP BY clause or be used in an aggregate functionSQL 必须出现在 GROUP BY 子句中或在聚合函数中使用
【发布时间】:2021-05-01 22:03:48
【问题描述】:

我有一条 SQL 语句

    sql = """
    insert into metadata (code, code_map, has_property) (
        select
            code,
            jsonb_agg(to_jsonb(new_code)) as code_map,
            has_property
        from data_to_data
        where code is not null
        group by 1
    ) on conflict (code) do update
    set code_map = excluded.code_map;
    """

以前 has_property 字段不存在,这工作正常。现在我已经添加了 has_property,我得到了错误

column "data_to_data.has_property" must appear in the GROUP BY clause or be used in an aggregate function

我明白这意味着什么,但我不确定如何解决这个问题。对于插入的任何等效代码,has_property 字段应该相同,所以我只想将它们聚合为一个布尔值。

这是数据示例

code, code_map, has_property
1, 2, True
1, 3, True
5, 6, False
5, 7, False

关于如何完成此任务的任何建议?

【问题讨论】:

    标签: sql python-3.x postgresql


    【解决方案1】:

    如果代码相同,将其包含在group by中并没有什么坏处:

    select code,
           jsonb_agg(to_jsonb(new_code)) as code_map,
           has_property
    from data_to_data
    where code is not null
    group by code, has_property;
    

    或者,使用聚合函数:

    select code,
           jsonb_agg(to_jsonb(new_code)) as code_map,
           bool_or(has_property) as has_property
    from data_to_data
    where code is not null
    group by code;
    

    【讨论】:

    • 我接受这个作为答案。在 postgresql 中,我不得不使用 bool_or 而不是 max 作为聚合函数。谢谢!
    猜你喜欢
    • 2015-08-14
    • 2013-11-05
    • 1970-01-01
    • 2013-08-06
    • 2018-05-16
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多