简体   繁体   中英

How can I sum on this query

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?

Because you're using postgres as reported by the error column "users.id" must appear in the GROUP BY clause . You should simply add Group by users.id at the end of your request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM