2012-12-03 52 views
0

我有這個查詢,讓我回來多個結果。我想編輯它,這樣它只會給我一個結果,每個o.Customer_ID,然後這就是今天最接近o.OrderPlaceServerTime的訂單。MySQL查詢。給最接近的日期至當前

這裏的查詢我:

SELECT 
    o.Order_ID, 
    o.Customer_ID, 
    o.OrderPlaceServerTime, 
    o.CustomerOrderTotal 
FROM 
    Orders o 
    LEFT JOIN Order_LineDetails oln 
    ON oln.Order_ID = o.Order_ID 
WHERE 
    o.OrderPlaceServerTime >= '2012-09-01 00:00:00' 
AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00' 
AND o.CustomerOrderTotal >= '50' 
AND oln.Product_ID = '75' 

什麼會,我需要改變,以實現這一目標?

+0

請問 '最接近的日期' 是'MAX(OrderPlaceServerTime)'? – Kermit

+0

是的,這是正確的。 – Monty

回答

1

我想編輯它,這樣它纔會給我一個結果每o.Customer_ID

所以,首先你應該得到的符合條件的客戶ID的最新訂單,通過分組預選賽按客戶ID訂購併選擇最大或OrderPlaceServerTime。然後,您會將這些記錄與訂單上的客戶ID和OrderPlaceServerTime結合起來,以選擇其他兩個感興趣的屬性。

SELECT 
    o.Order_ID, 
    o.Customer_ID, 
    o.OrderPlaceServerTime, 
    o.CustomerOrderTotal 
FROM 
    Orders o 
    JOIN (
     SELECT 
      o.Customer_ID, 
      MAX(o.OrderPlaceServiceTime) 'MaxOrderPlaceServiceTime' 
     FROM 
      Orders o 
      LEFT JOIN Order_LineDetails oln 
      ON oln.Order_ID = o.Order_ID 
     WHERE 
      o.OrderPlaceServerTime >= '2012-09-01 00:00:00' 
     AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00' 
     AND o.CustomerOrderTotal >= '50' 
     AND oln.Product_ID = '75' 
     GROUP BY o.Customer_ID 
    ) AS A 
    ON 
     o.Customer_ID = A.Customer_ID AND 
     o.OrderPlaceServiceTime = A.MaxOrderPlaceServiceTime 
+0

這看起來不錯,但它返回0結果。 – Monty

+0

我忘了在內部查詢中添加一個「GROUP BY」。你想再試一次嗎? – Vikdor

+0

太好了,謝謝! – Monty

0

如果我理解正確的,你需要的東西,這應該是查詢:

SELECT * FROM 

    (SELECT 
    o.Order_ID, 
    o.Customer_ID, 
    o.OrderPlaceServerTime, 
    o.CustomerOrderTotal 
    FROM 
     Orders o 
     LEFT JOIN Order_LineDetails oln 
     ON oln.Order_ID = o.Order_ID 
    WHERE 
     o.OrderPlaceServerTime >= '2012-09-01 00:00:00' 
    AND o.OrderPlaceServerTime <= '2012-12-01 00:00:00' 
    AND o.CustomerOrderTotal >= '50' 
    AND oln.Product_ID = '75'  
    ORDER BY o.Customer_ID, o.OrderPlaceServerTime DESC) AS tab1 

    GROUP BY o.Customer_ID; 
相關問題