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

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

我的查询出错了。 为什么? 我不明白:(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    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


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

文档说:

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.