Subject | Re: SQL - Most recent order for each product |
---|---|
Author | radevojvodic |
Post date | 2004-09-29T08:16:49Z |
Try this one. I have a similar query that works. If you have
different prices on same date you should probably use Max(I.Price)
if you want higher price
SELECT
DISTINCT
P.PRODUCT_ID,
O1.ORDER_DATE,
Max(O2.ORDER_DATE)
I.PRICE
FROM PRODUCTS P
JOIN ORDER_ITEMS I
ON P.PRODUCT_ID = I.PRODUCT_ID
JOIN ORDERS O1
ON I.ORDER_ID = O1.ORDER_ID
JOIN ORDERS O2
ON O1.ORDER_ID = O2.ORDER_ID
JOIN CUSTOMER C
ON C.CUSTOMER_ID = O1.CUSTOMER_ID
WHERE
C.CUSTOMER_ID = 10300
GROUP BY P.PRODUCT_ID, O.ORDER_DATE, I.PRICE
HAVING O1.ORDER_DATE = MAX(O2.ORDER_DATE)
ORDER BY 1,2
different prices on same date you should probably use Max(I.Price)
if you want higher price
SELECT
DISTINCT
P.PRODUCT_ID,
O1.ORDER_DATE,
Max(O2.ORDER_DATE)
I.PRICE
FROM PRODUCTS P
JOIN ORDER_ITEMS I
ON P.PRODUCT_ID = I.PRODUCT_ID
JOIN ORDERS O1
ON I.ORDER_ID = O1.ORDER_ID
JOIN ORDERS O2
ON O1.ORDER_ID = O2.ORDER_ID
JOIN CUSTOMER C
ON C.CUSTOMER_ID = O1.CUSTOMER_ID
WHERE
C.CUSTOMER_ID = 10300
GROUP BY P.PRODUCT_ID, O.ORDER_DATE, I.PRICE
HAVING O1.ORDER_DATE = MAX(O2.ORDER_DATE)
ORDER BY 1,2