Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple sum()s in ActiveRecord in Rails

I'd like to link multiple sums() to a single group by while selecting other fields at the same time. I'd also prefer to use the ActiveRecord methods to do this rather than construct a sql string manually, as I may modify the behavior of inherited classes of ActiveRecord later.

For example I'd like to represent the statement (as an example)

select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id

with something like:

LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)

The reason being I may add additional group-bys and where-clauses later, which all the sums will have in common.

like image 497
inyourcorner Avatar asked Apr 13 '11 23:04

inyourcorner


1 Answers

This works for me:

require "active_record"
require "logger"

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection :adapter => "postgresql", :database => "francois"

ActiveRecord::Base.connection.execute "DROP TABLE IF EXISTS values"
ActiveRecord::Base.connection.execute "CREATE TABLE values(user_id INTEGER NOT NULL, quantity INTEGER NOT NULL DEFAULT 1, cost INTEGER NOT NULL DEFAULT 2)"

class Value < ActiveRecord::Base
end

2.times do
  5.times do |n|
    Value.create!(:user_id => n)
  end
end

Value.group(:user_id).select('user_id, SUM(cost) AS total_cost, SUM(quantity) AS total_quantity').each do |value|
  p [value.user_id, value.total_quantity, value.total_cost]
end

I tried sum(:cost, :quantity), but #sum doesn't expect arguments defined this way. I also tried sum(:cost => :total_cost, :quantity => :total_quantity), to no avail.

like image 195
François Beausoleil Avatar answered Nov 14 '22 16:11

François Beausoleil