PGError: ERROR: the column "p.name" should appear in the GROUP BY clause or be used in an aggregate function

I get an error with this request. What for? I do not 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
+3
source share
1 answer

Change GROUP BY project_idtoGROUP BY p.name,p.id

The docs say:

If present GROUP BY, it is SELECTnot valid for list expressions to reference non-group columns, except within aggregate functions, since more than one possible value will be returned for a non-group column.

+10
source

Source: https://habr.com/ru/post/1787539/


All Articles