Question

An account has_many loans and a loan has fee and amount fields.

For a given account, I am trying to gather the total number of loans and the sums of the fee and amount fields.

I want to cut this down to 1 DB query for efficiency.

# Trying to combine these 3 queries into 1
total_loans  = Loan.where(account_id: 1).size
total_fees   = Loan.where(account_id: 1).sum(:fee)
total_amount = Loan.where(account_id: 1).sum(:amount)

I've been trying to understand the PG GroupingError but I don't have adequate knowledge about PG and RDBMs to figure this out. Honestly, I've read several SO questions about similar topics and have Googled it but I simply cannot understand how the grouping idea works.

# Tried this but does not work (PG::GroupingError, must have "loans.id" in group_by)
stats = Loan.where(account_id: 1).select("count(id) as total_loans, sum(fee) as total_fees, sum(amount) as total_amount").group("account_id, id")

I would like to be able to say stats.total_loans, stats.total_fees, etc...

Était-ce utile?

La solution

You can include id into group by select clause only if it in group by statement. So, if you need count of grouped results you just need count(*) instead of count(id).

Also read this.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top