0

I currently have a table called pairs_of_products that has the following two columns:

product_id_1, product_id_2

I would like to create a temporary table called monthly_orders that will have the following columns:

product_id, monthly_orders

and then join it to pairs_of_products so that I can end up with a new table with the following columns

product_id_1, product_id_2, monthly_orders_1, monthly_orders_2

I am not sure how to go about this in an efficient way - though I am sure that I would like to only create monthly_orders once.

4

1 回答 1

1

第 1 步:创建monthly_orders.

第二步:查询:

SELECT pp.product_id_1,
       pp.product_id_2,
       mo1.monthly_orders AS monthly_orders_1,
       mo2.monthly_orders AS monthly_orders_2
  FROM pairs_of_products pp
  JOIN monthly_orders mo1
    ON pp.product_id_1 = mo1.product_id
  JOIN monthly_orders mo2
    ON pp.product_id_2 = mo2.product_id
;

编辑添加:或者,一步:

  WITH monthly_orders AS
       ( SELECT ... AS product_id,
                ... AS monthly_orders
           FROM ...
       )
SELECT pp.product_id_1,
       pp.product_id_2,
       mo1.monthly_orders AS monthly_orders_1,
       mo2.monthly_orders AS monthly_orders_2
  FROM pairs_of_products pp
  JOIN monthly_orders mo1
    ON pp.product_id_1 = mo1.product_id
  JOIN monthly_orders mo2
    ON pp.product_id_2 = mo2.product_id
;

(使用子查询分解)。

于 2013-06-17T03:43:09.757 回答