I have the following setup.
Invoice has_many Jobs has_many Tasks belongs_to user
I want to get all User
s for an Invoice
that have tasks and sum up their quantities
class Invoice < ActiveRecord::Base
has_many :jobs
end
class Job < ActiveRecord::Base
belongs_to :invoice
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :job
belongs_to :user
end
Here is what I got
@invoice = Invoice.find(params[:id])
jobs = @invoice.jobs.joins(:tasks)
.select('tasks.user_id, (sum(tasks.quantity)*jobs.price) as total')
.group('tasks.user_id, jobs.id')
.order('tasks.user_id')
I get this, which is close to what I want
- !ruby/object:Job
attributes:
user_id: '1'
total: '60.00'
- !ruby/object:Job
attributes:
user_id: '1'
total: '50.00'
- !ruby/object:Job
attributes:
user_id: '2'
total: '120.00'
- !ruby/object:Job
attributes:
user_id: '2'
total: '100.00'
How can I group this by user_id
and sum up the total so that I have something like this?
user_id: 1
total: 110
user_id: 2
total: 220
Use the PHP array_reduce () function to GROUP BY and SUM values of an array in PHP. In this example, we will show you how to group array by key and sum values using PHP. It helps to sum the values of an array with the same keys in PHP.
SUM() function with group by. SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group.
SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.
Use Array#reduce with a helper object to group similar objects. For each object, check if the combined shape and color exists in the helper. If it doesn’t, add to the helper using Object#assign to create a copy of the object, and push to the array. If it does, add it’s values to used and instances.
thansk for your answers.
I managed to solve this with
user_totals = jobs.to_a.group_by(&:user_id).map{ |user_id,jobs| {:user_id => user_id.to_i, :total => jobs.sum {|j| j.total.to_f} }}
=> [{:user_id=>1, :total=>110.0}, {:user_id=>2, :total=>220.0}]
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