Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping an array and get sum

I have the following setup.

Invoice has_many Jobs has_many Tasks belongs_to user

I want to get all Users 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
like image 524
Stefan Mielke Avatar asked Mar 26 '13 11:03

Stefan Mielke


People also ask

How to group by and sum values of an array in PHP?

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.

How do you use sum in a group by clause?

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.

How to use Sum Sum in SQL?

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.

How do you group similar objects together in Python?

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.


1 Answers

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}]
like image 198
Stefan Mielke Avatar answered Oct 04 '22 16:10

Stefan Mielke