PGError: ERROR: column “p.name” must appear in the GROUP BY clause or be used in an aggregate function

我与影子孤独终老i 提交于 2019-11-28 09:22:49

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/4786768/pgerror-error-column-p-name-must-appear-in-the-group-by-clause-or-be-used-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!