我有一张满足购买价格的表格,如下:
sku price btw startdate PCR-CA5425023181515 21,17 € 1 01/01/2009 PCR-CA5425023181515 999,00 € 1 06/06/2009 PCR-CA5425023181515 444,00 € 4 09/07/2009 PCR-CA5425023181515 100,00 € 4 10/08/2009
我还有另一张表,里面装满了订单,如下:
sku quantity orderdate PCR-CA5425023181515 5 01/05/2009 PCR-CA5425023181515 10 01/12/2009 PCR-CA5425023181515 10 24/12/2009
我的目标是从该日期起获得每个订单的每个购买价格。 (例如:当我在5月1日(01/05)订购产品时,它的成本为21,17欧元。 当我在12月1日(01/12)订购它时,它花费了100,00欧元。)
过去一小时我一直在努力,但还没找到任何有用的东西。
答案 0 :(得分:1)
SELECT
O.sku,
O.qty,
PP.price
FROM
Orders O
INNER JOIN Purchase_Prices PP ON
PP.sku = O.sku AND
PP.start_date <= O.order_date
WHERE
NOT EXISTS
(
SELECT
*
FROM
Purchase_Prices PP2
WHERE
PP2.sku = PP.sku AND
PP2.start_date <= O.order_date AND
PP2.start_date > PP.start_date
)
可替换地:
SELECT
O.sku,
O.qty,
PP.price
FROM
Orders O
INNER JOIN Purchase_Prices PP ON
PP.sku = O.sku AND
PP.start_date <= O.order_date
LEFT OUTER JOIN Purchase_Prices PP2 ON
PP2.sku = O.sku AND
PP2.start_date <= O.order_date AND
PP2.start_date > PP.start_date
WHERE
PP2.sku IS NULL