I'm trying to group quotes sum per month, while adding last sums.
For example:
Jan: 300€
Fev: 200€
Mars: 100€
What the group should return is:
Jan:300€
Fev: 500€ (200 + Jan's 300)
Mars: 600€ (100 + Fev's 500)
Current SQL:
current_user.quotes.group_by_month(:created_at, last: 12).sum(:price)
I'm using the groupdate gem.
Thanks.
If used postgresql you can use windows function
UNBOUNDED PRECEDING first row,CURRENT ROW current rowssum function to Accumulatelike this.
select name,sum(price)
over(order by (select 1) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) "price"
from T
sqlfidde:http://sqlfiddle.com/#!17/763e3/7
Widows function
Solution in Ruby:
s = 0
current_user.quotes.group_by_month(:created_at, last: 12).
sum(:price).
transform_values.map { |v| s += v }
as there is only a hash of 12 elements, i suggest the performance penalty of using ruby instead of sql are marginal. Using SQL would be much harder and not possible only with simple ActiveRecord Arel methods or probably database specific, see e.g. Calculating Cumulative Sum in PostgreSQL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With