views:

30

answers:

1

I have a table filled with purchase prices, like this:

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

I have another table filled with orders, like this:

sku                  quantity   orderdate
PCR-CA5425023181515     5       01/05/2009
PCR-CA5425023181515    10       01/12/2009
PCR-CA5425023181515    10       24/12/2009

My goal is to get every purchase price per order from that date. (For example: when I ordered the product on the first of may (01/05) it cost 21,17 euros. When I ordered it on the first of december (01/12) it cost 100,00 euros.)

I've been struggling with this for the past hour, but haven't found anything useful yet.

+1  A: 
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
     )

Alternatively:

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
Tom H.
That's exactly it! The first one, with the subquery, works like a charm.I was also trying out something with a WHERE EXISTS, but had multiple subqueries. It didn't pan out.The second one didn't work, however. Access complained about missing operators. (Which is obviously not true)
skerit
Beware because subqueries with NOT are not well-optimized in Jet/ACE and don't always use the indexes on both sides of the criterion. NOT EXISTS is even worse in this regard than NOT IN, which uses both indexes the majority of the time. The cases when it doesn't work are not entirely predictable, and since it may have something to do with metadata, a NOT subquery that's not a performance pig today may be one under some other circumstances after more records are involved, for instance.
David-W-Fenton