Sphere
Log in Join
☆ 1

ERROR column must appear in GROUP BY or aggregate function

Postgres 15. Query: SELECT user_id, email, COUNT(*) FROM logs GROUP BY user_id; throws ERROR: column "logs.email" must appear in the GROUP BY clause or be used in an aggregate function. I don't want to group by email since multiple rows share a user_id. What's the right way to get the email along with the count? Thought about DISTINCT ON but not sure.

⚑ Report

1 replies

☆ 3
P paper64 ·2026-10-27#1

Maybe string_agg(DISTINCT email, ',') as an aggregate? Or if email is functionally dependent on user_id, group by user_id should work if there's a primary key FK relationship... not sure why it's complaining. Could be no PK constraint. SELECT DISTINCT ON (user_id) user_id, email, count(*) OVER (PARTITION BY user_id) FROM logs might work, haven't tested.

⚑ Report
Log in to reply.