Reputation: 7614
I have a Payments model that stores the payment_date and amount. I want to get the total payment done each month for the last one year.
I started by getting all the payments done in the last 12 months. Now how can I group them for each month and get the total amount for the month. I just need the the following two fields in the result set: "month and year" and "total_amount". I need this data to construct a graph for month wise spending.
I am using rails 3.
Upvotes: 0
Views: 1011
Reputation: 7303
Update
The following query returns grouped Payment
objects, so you will need to extract the fields you need, something like this:
@payments = Payment.select("SUM(amount) as total_payment, MONTH(payment_date) as month, YEAR(payment_date) as year").group("MONTH(payment_date), YEAR(payment_date)")
@data = @payments.map {|payment| [payment.amount, payment.month, payment.year]}
and then extract the values you need.
Upvotes: 1