我想在同时选择其他字段时将多个sums()链接到单个组。我也更喜欢使用ActiveRecord方法来执行此操作而不是手动构造sql字符串,因为我可能稍后修改ActiveRecord的继承类的行为。
例如,我想代表声明(作为例子)
select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id
有类似的东西:
LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)
原因是我可能会在以后添加额外的分组和where子句,所有的总和将具有共同点。
答案 0 :(得分:19)
这对我有用:
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
我尝试sum(:cost, :quantity)
,但#sum
不希望以这种方式定义参数。我也试过sum(:cost => :total_cost, :quantity => :total_quantity)
,但没有用。