加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 21:58:46 所属栏目:百科 来源:网络整理
导读:我想通过同时选择其他字段来将多个sums()链接到一个单独的组.我也更喜欢使用ActiveRecord方法来执行此操作,而不是手动构造一个sql字符串,因为我可以稍后修改继承的ActiveRecord类的行为. 例如,我想表示声明(举个例子) select user_id,sum(cost) as total_cos
我想通过同时选择其他字段来将多个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),没有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读