I'm using Postgres. This returns all payments grouped by user which works fine.
@users_with_payments = Payment.all(select: 'distinct(users.*)', joins: :user)
I need to sum the total payments amounts for each user to order by that amount. When trying this I get this error
@users_with_payments = Payment.all(select: 'distinct(users.*), SUM(payments.amount_cents)', joins: :user)
PG::Error: ERROR: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT distinct(users.*), SUM(payments.amount_cents) FROM "p...
Any idea what I'm doing wrong and what would be the right way to construct this query?