如何按周划分我的帐户余额?

时间:2016-05-13 07:57:19

标签: ruby-on-rails ruby postgresql activerecord

我有一个模型账户,可以通过活动看到余额增长。有没有办法分组并获得该周的最终余额?这里有一个例子:

帐户

created_at: 31 April 2016, balance: 8000  # Saturday
created_at: 1 May 2016, balance: 7500     # Sunday
created_at: 1 May 2016, balance: 7000     # Sunday
created_at: 7 May 2016, balance: 5000     # Saturday
created_at: 7 May 2016, balance: 4000     #    "
created_at: 8 May 2016, balance: 3500     # Sunday
created_at: 12 May 2016, balance: 7000    # Thursday

让我们说周末的结束时间是每个星期一。我的预期结果将是:

{
  2 May 2016 => 7000,    # Monday
  9 May 2016 => 3500,    # Monday
  13 May 2016 => 7000    # Today
}

我希望每个星期一都有余额,但加上最近的余额,即使不在星期一。

1 个答案:

答案 0 :(得分:1)

按年度和年份对结果进行分组:

.group("extract(dow from 'created_at'), extract(week from 'created_at')")

然后选择余额之和:

.select("sum(balance)")