我该如何总结这个查询

时间:2013-08-26 16:47:39

标签: ruby-on-rails postgresql

我正在使用Postgres。这将返回按用户分组的所有付款,工作正常。

@users_with_payments = Payment.all(select: 'distinct(users.*)', joins: :user)

我需要将每个用户的总付款金额相加到该金额。尝试这个时我得到了这个错误

@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...

知道我做错了什么以及构建这个查询的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

因为您使用错误column "users.id" must appear in the GROUP BY clause报告的 postgres 。您只需在请求结束时添加Group by users.id即可。