Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group and sum all currencies

I hope the title is correct. I need to sum all currencies ie all of $, £ etc, but not to combine all into one sum.

Basically if I have 2x $4 and 3x £10, that will be $8 and £30

I have an Income model with attributes :currency (string) and :amount (float):

What I have works but I feel it can refactor a bit:

Income.all.group(:currency).count.map do |k,v|
  Income.where(currency: k).map.sum(&:amount)
end

That gives me an array of the total. Ok-ish. I needed a more nicer format such as an Hash:

{
  USD => 8.0,
  GBP => 30.0
}

Possible? How, please?

like image 649
Sylar Avatar asked Dec 20 '25 22:12

Sylar


1 Answers

I think the following would do:

Income.group(:currency).sum(:amount)

The SQL would looks like:

SELECT SUM(income.amount) AS sum_amount, currency AS currency
  FROM income
  GROUP BY income.currency
like image 151
Andrey Deineko Avatar answered Dec 22 '25 15:12

Andrey Deineko