PGError:错误:列“p.name”必须出现在 GROUP BY 子句中或在聚合函数中使用

发布于 2024-10-14 15:41:37 字数 729 浏览 1 评论 0原文

我收到此查询错误。为什么?我不明白 :(

    SELECT p.name, p.id, SUM(hours) AS hours, SUM(logged_hours) AS logged_hours
    FROM (
        SELECT project_id, date, hours, null AS logged_hours
        FROM #{ScheduleEntry.table_name}
        WHERE user_id = #{User.current.id}
            AND date BETWEEN '%s' AND '%s'
        UNION
        SELECT project_id, spent_on AS date, null AS hours, sum(#{TimeEntry.table_name}.hours) AS logged_hours
        FROM #{TimeEntry.table_name}
        WHERE user_id = #{User.current.id}
            AND spent_on BETWEEN '%s' AND '%s'
        GROUP BY project_id, date
    ) AS results
    LEFT JOIN #{Project.table_name} AS p ON p.id = results.project_id
    GROUP BY project_id

I get an error with this query. Why? I don't understand :(

    SELECT p.name, p.id, SUM(hours) AS hours, SUM(logged_hours) AS logged_hours
    FROM (
        SELECT project_id, date, hours, null AS logged_hours
        FROM #{ScheduleEntry.table_name}
        WHERE user_id = #{User.current.id}
            AND date BETWEEN '%s' AND '%s'
        UNION
        SELECT project_id, spent_on AS date, null AS hours, sum(#{TimeEntry.table_name}.hours) AS logged_hours
        FROM #{TimeEntry.table_name}
        WHERE user_id = #{User.current.id}
            AND spent_on BETWEEN '%s' AND '%s'
        GROUP BY project_id, date
    ) AS results
    LEFT JOIN #{Project.table_name} AS p ON p.id = results.project_id
    GROUP BY project_id

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好听的两个字的网名 2024-10-21 15:41:37

GROUP BY project_id 更改为 GROUP BY p.name,p.id

文档 说:

当存在 GROUP BY 时,SELECT 列表表达式引用未分组的列(聚合函数内除外)是无效的,因为可能有多个可能为未分组的列返回的值。

Change GROUP BY project_id to GROUP BY p.name,p.id

The docs say:

When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, since there would be more than one possible value to return for an ungrouped column.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文