やりたいこと
商品テーブルと集計した注文テーブルを結合したい
詳細
・商品テーブル(Product) cd | 名前 1 | 本 2 | ペン 3 | ノート ・注文テーブル(ReceiveOrder) 商品cd | 注文数 | 注文日 | 出荷日 1 | 1 | 2/1 | 2/1 2 | 2 | 2/2 | 2/11 3 | 2 | 2/2 | 3/1 1 | 4 | 2/27 | 2/28 1 | 1 | 2/28 | 3/2 1 | 3 | 3/1 | null
というデータがあるときに
①注文テーブルの注文日が2/1~2/28の合計数が「注文数」
商品cd | 注文数 1 | 6 2 | 2 3 | 2
②注文テーブルの出荷日が2/1~2/28の合計数が「出荷数」
商品cd | 出荷数 1 | 1 2 | 2
というように整形して、
商品テーブルと①と②を商品cdをキーとして結合して下記のようなデータを取得したい
商品cd | 名前 | 注文数 | 出荷数 1 | 本 | 6 | 1 2 | ペン | 2 | 2 3 | ノート | 2 | 0
関連するプログラムなど
class Product < ApplicationRecord has_many :receive_orders , -> {} , class_name: 'ReceiveOrder', primary_key: :product_cd, foreign_key: :product_cd, dependent: :destroy has_many :shipping_orders , -> { where.not( shipping_orders: {shippings_in: nil}) } , class_name: 'ReceiveOrder', primary_key: :product_cd, foreign_key: :product_cd, dependent: :destroy accepts_nested_attributes_for :receive_orders, allow_destroy: true accepts_nested_attributes_for :shipping_orders, allow_destroy: true end
class ReceiveOrder < ApplicationRecord belongs_to :product , primary_key: :product_cd , foreign_key: :product_cd, optional: true scope :receive_period, -> (from, to) { where(receive_order_in: from..to) } scope :shipping_period, -> (from, to) { where(shippings_in: from..to) } end
from="2020-02-01".to_date.beginning_of_day to="2020-02-29".to_date.end_of_day # 期間内の注文数 period_receive_order = ReceiveOrder.receive_period(from, to).group("product_cd").select("product_cd, sum(quantity) as amount") # 期間内の出荷数 period_shipped_order = ReceiveOrder.shipping_period(from, to).where.not(shippings_in: nil).group("product_cd").select("product_cd, sum(quantity) as amount") # group化しない結合は下記で取得できました order = Product.eager_load(:receive_orders, :shipping_orders).joins("AND receive_orders.receive_order_in BETWEEN '#{from}' AND '#{to}' AND shipping_orders_products.shippings_in BETWEEN '#{from}' AND '#{to}'")
現状
注文テーブルから個別に注文数と出荷数の取得はできた。
集計していなければ、left_joinで結合はできたが、取得したい値ではない。
集計結果を結合する方法のご教授をお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。