繁体   English   中英

Rails 3中可能使用范围的多个SUM语句或子查询。 任何人?

[英]Multiple SUM statements or subqueries in Rails 3, possibly using scope. Anyone?

对于3类的Rails

class Item < ActiveRecord::Base
  has_many :production_runs
  has_many :deliveries
end

生产运行和交付都具有该特定生产或交付中项目数的“数量”属性。

我想查询项目,并(也许使用作用域?)将两个表中数量的Sum()添加到结果中。 就像是:

select items.*, (select SUM(production_runs.quantity) as runs from production_runs where production_runs.item_id = 42), (select SUM(deliveries.quantity) as dels from deliveries where deliveries.item_id = 42) from items where items.id = 42;

这可以为单个项目提供正确的结果,但我想以某种方式将这些总和汇总为更一般的查询。

我尝试了各种向Item和ProductionRun和Delivery类添加作用域的过程,但是没有运气。 最好使用范围,因为我可以根据需要将其与其他条件链接起来,但是实际上,我对任何比找到项目集然后进行迭代都更优化的通用解决方案感到满意。

有人知道最好的方法吗?

谢谢

scope :sum_column_name, lambda{
    sum("column name")}

应该管用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM