ruby-on-rails – Rails中的ActiveRecord中有多个sum()

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails中的ActiveRecord中有多个sum()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过同时选择其他字段来将多个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-clause,这些都是共同的.

解决方法

这对我有用:
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),没有用.

猜你在找的Ruby相关文章