轨道:在添加最后一个值(斐波那契)时分组和求和



我正在尝试对每月的报价总和进行分组,同时添加最后一个总和。

例如:

Jan: 300€
Fev: 200€
Mars: 100€

组应返回的内容是:

Jan:300€
Fev: 500€ (200 + Jan's 300)
Mars: 600€ (100 + Fev's 500)

当前 SQL:

current_user.quotes.group_by_month(:created_at, last: 12).sum(:price)

我正在使用groupdate宝石。

谢谢。

如果使用postgresql您可以使用windows 函数

  1. UNBOUNDED PRECEDING第一行,CURRENT ROW当前行
  2. 使用sum函数累积

喜欢这个。

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

寡妇功能

Ruby 中的解决方案:

s = 0
current_user.quotes.group_by_month(:created_at, last: 12).
sum(:price).
transform_values.map { |v| s += v }

由于只有 12 个元素的哈希值,我建议使用 Ruby 而不是 SQL 的性能损失是微不足道的。使用SQL会困难得多,并且仅使用简单的ActiveRecord Arel方法或可能特定于数据库的方法是不可能的,例如参见PostgreSQL中的计算累积总和。

我们可以使用以下代码

quotes = current_user.quotes
sum = 0
quotes.each_with_object({}) do |quote,hassh|
hassh[quote.name] = sum = quote.price + sum
end
hassh

最新更新