Multiple sum()s in ActiveRecord in Rails

試著忘記壹切 提交于 2019-12-22 03:50:59

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5656907/multiple-sums-in-activerecord-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!