GroupingError: ERROR: column “ ” must appear in the GROUP BY clause or be used in an aggregate function

后端 未结 1 2492
忘掉有多难
忘掉有多难 2020-12-06 14:48

I am trying to create a list of unique patients who have left comments. The code words fine until I upload to heroku where it doesnt work in postgresql.

This is my

相关标签:
1条回答
  • 2020-12-06 15:15

    You cannot combine SELECT * with GROUP BY some_column in Postgres (unless some_column is the PK), because that's a contradiction. All non-aggregated columns (used in the SELECT, HAVING or ORDER BY clause outside an aggregate function) must be in the GROUP BY list - where the primary key column can replace all columns of a table. Else it is undefined which value to pick from the aggregated set.

    Per documentation:

    When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

    A certain other RDBMS is known to play dirty tricks here and allow this and pick arbitrary values...

    You seem to want a list of unique patients that have commented, with the latest comment each. The simplest way in Postgres is with DISTINCT ON:

    SELECT DISTINCT ON (patient_id) *
    FROM   comments
    WHERE  clinician_id = $1
    ORDER  BY patient_id, created_at DESC NULLS LAST;
    

    But this won't fly with SQLite - which should not be in the loop to begin with:

    • Generic Ruby solution for SQLite3 "LIKE" or PostgreSQL "ILIKE"?

    NULLS LAST is only relevant if created_at can be NULL:

    • PostgreSQL sort by datetime asc, null first?

    Details for DISTINCT ON:

    • Select first row in each GROUP BY group?
    0 讨论(0)
提交回复
热议问题