Rails 4: group by month

In Rails / Ruby, how to group and aggregate a monthly measure based on a date column in a table.

I tried the following technique from Railscasts.

http://railscasts.com/episodes/29-group-by-month

So far my code looks like this

result = result.where(transaction_date: start..Date.current)
result = result.select(:transaction_date, :quantity)
result.group_by { |t| t.transaction_date.beginning_of_month }

I guess I need the Ruby equivalent of SQL GROUP BY to accumulate the amount.

The version of SQLite3 I'm looking for:

select strftime('%m', transaction_date)
     , sum(quantity)
from transactions
group by strftime('%m', transaction_date)
+5
source share
1 answer

So this is a good example of why you should use the same database in dev and prod, because you really want to do this in SQL, which will be different for the two databases you specify. I will give you a version of Postgres.

, "", , - :

Entity
  .select("DATE_TRUNC('month', created_at) AS month, SUM(quantity) AS total_quantity")
  .group('month')

Entity "month" "total_quantity", .

+5

All Articles