iny*_*ner 10 activerecord ruby-on-rails
我想在同时选择其他字段时将多个sums()链接到一个组.我也更喜欢使用ActiveRecord方法来做这个而不是手动构造一个sql字符串,因为我可以稍后修改ActiveRecord的继承类的行为.
例如,我想代表声明(作为例子)
select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id
Run Code Online (Sandbox Code Playgroud)
有类似的东西:
LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)
Run Code Online (Sandbox Code Playgroud)
原因是我可能会在以后添加额外的分组和where子句,所有的总和将具有共同点.
Fra*_*eil 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
Run Code Online (Sandbox Code Playgroud)
我尝试过sum(:cost, :quantity),但#sum不要指望以这种方式定义参数.我也试过sum(:cost => :total_cost, :quantity => :total_quantity),无济于事.
| 归档时间: |
|
| 查看次数: |
6210 次 |
| 最近记录: |