gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:26:00 28 4
gpt4 key购买 nike

我想通过同时选择其他字段来将多个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-子句,所有这些总和将具有共同点。

最佳答案

这对我有用:

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-on-rails - Rails中ActiveRecord中的多个sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5656907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com