【问题标题】:has_many with sum active recordhas_many 有总和活动记录
【发布时间】:2015-07-07 07:27:45
【问题描述】:
class Product < ActiveRecord::Base

      belongs_to  :category
      has_many  :order_items, dependent: :destroy
    end


class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :product
end

我需要列出所有产品及其 order_item 中的数量总和以及它们的总价格总和

Product
id    name
1    product_1

OrderItem
product_id order_id quantity total_price
 1            1      10        200
 1            2      10        200

for example expecting output should be
name       quantity   total_price
product_1  20         400

【问题讨论】:

  • 谢谢@jarlh,这可能像 Product.joins(:order_items).sum("order_items.quantity") 吗?

标签: mysql sql ruby-on-rails activerecord


【解决方案1】:
select p.name, sum(o.quantity) as quantity, sum(o.total_price) as total_price
from Product p
  join OrderItem o on p.id = o.product_id
group by p.name

【讨论】:

  • 谢谢@jarlh。一个小的修改“选择 p.name,sum(o.quantity) 作为数量,sum(o.total_price) 作为来自产品 p 的总价格加入 order_items o on p.id = o.product_id group by p.name”
  • 如何在此处添加 where 条件,我尝试“选择 p.name,sum(o.quantity) 作为数量,sum(o.total_price) 作为来自产品 p 的总价格加入 order_items o on p。 id = o.product_id group by p.name WHERE (o.created_at = '2015-07-07')" ?
  • 只需将 WHERE 放在 GROUP BY 之前。
  • 感谢您的工作。 “选择 p.name,sum(o.quantity) 作为数量,sum(o.total_price) 作为来自产品 p 的 total_price 加入 order_items o on p.id = o.product_id WHERE (DATE(o.created_at) = '2015-07 -07') 按 p.name 分组"
【解决方案2】:

试试这个查询

select a.name,sum(quantity) as quantity ,sum(total_price) as total_price from 
Product a
join OrderItem b on a.id=b.product_id
Group by a.name

【讨论】:

  • 谢谢@Mukesh Kalgude。在您的查询中进行小修改,以帮助其他人“选择 a.name,sum(b.quantity) 作为数量,sum(b.total_price) 作为来自产品 a 的总价格 a 加入 order_items b on a.id=b.product_id Group by a。名字”
  • 抱歉,我无法选择两个正确答案。既然他先回复了,我就接受了他的回复。谢谢
  • 如何在此处添加 where 条件,我尝试“选择 p.name,sum(o.quantity) 作为数量,sum(o.total_price) 作为来自产品 p 的总价格加入 order_items o on p。 id = o.product_id group by p.name WHERE (o.created_at = '2015-07-07')" ?
【解决方案3】:

试试这个进行活动记录查询。只需验证您可以使用的列、表名和关联,例如:

   OrderItem.joins(:product).select("products.name as name,sum(total_price) as total_price , sum(quantity) as total_quantity").group("order_items.product_id").as_json

【讨论】:

    【解决方案4】:
    p = Product.first
    p.order_items.sum(:quantity)
    

    我希望这也能有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多