Search code examples
sqlpostgresqlnode-postgres

Postgresql error: column must appear in the GROUP BY clause or be used in an aggregate function


Message table from where i want to get recent contacts for 'user1', now the table looks like this:

| id | receiver | sender | time       |
|----|----------|--------|------------|
| 1  | user1    | host1  | 2020-07-02 |
| 2  | host2    | user1  | 2020-07-03 |
| 3  | user3    | host3  | 2020-07-04 |

I managed to get the expected result by using mysql:

SELECT CASE WHEN receiver = 'user1' THEN sender ELSE receiver END AS id, max(time) AS time 
FROM message WHERE receiver = 'user1' OR sender = 'user1' 
GROUP BY CASE WHEN receiver = 'user1' THEN sender ELSE receiver END;

But when i run this query on postgres i get the error: Postgresql error: column receiver must appear in the GROUP BY clause or be used in an aggregate function. Any solution to fix this problem?


Solution

  • I would suggest distinct on:

    select distinct on ( case when receiver = 'user1' then sender else receiver end ) m.*
    from messages m
    where 'user1' in (receiver, sender)
    order by (case when receiver = 'user1' then sender else receiver end), time desc;