2016-12-02 72 views
0

我有2個表的一個客戶,一個與訂單MySQL查詢客戶選擇在每年沒有訂單

SELECT customers.customer_name, orders.order_date 
FROM customers 
Left 
Join orders on (customers.customer_id = orders.customer_id) 
WHERE not orders.customer_id IN (SELECT customer_id from orders where Year(order_date) = Year(@Parameter1)) 
and not orders.order_date is null 

這個工作,但我希望每一年這樣做是爲了得到這樣的財產以後的結果

|Year | customer_id | 
|2010 | 1   | 
|2010 | 2   | 
|2011 | 2   | 
|2011 | 3   | 
|2012 | 1   | 
+0

我認爲你可以做到這一點 '選擇年份(orders.order_date),客戶。 CUSTOMER_ID 客戶 左 加入上(customers.customer_id = orders.customer_id) 訂單WHERE NOT IN orders.customer_id(選擇訂單CUSTOMER_ID其中year(order_date的)=年(@參數1)) 而不是orders.order_date是空' 測試它並讓我知道。 – Ravenix

+2

@Ravenix我認爲你可以將它作爲答案而不是評論。 – Hermanto

回答

0

你要顯示的客戶和年份是出現在訂單表列表。因此,讓所有的客戶提供所有年份相結合的列表,然後減去您在訂單表中找到客戶和期限:

select o.yr, c.customer_id 
from customers c 
cross join (select distinct year(order_date) as yr from orders) o 
where (c.customer_id, o.yr) not in (select customer_id, year(order_date) from orders); 
+0

感謝您的幫助,這工作。 –

0

天蠍座是有點權,你必須使用一年函數:

SELECT Year(orders.order_date), customers.customer_id 
FROM customers 
LEFT JOIN orders 
ON (customers.customer_id = orders.customer_id) 
WHERE NOT orders.customer_id 
IN (
    SELECT customer_id 
    FROM orders 
    WHERE Year(order_date) = Year(@Parameter1) 
) 
AND 
NOT orders.order_date is NULL 

您可以使用日Ë一年方法在查詢中的SELECT部分​​

更新:

要顯示所有誰沒有在一年內訂購的客戶,你不需要加入。你可以用一個子查詢做到這一點:

SELECT @Parameter1 AS Year, customer_id 
FROM customers 
WHERE customers.customer_id NOT IN (
    SELECT customer_id 
    FROM orders 
    WHERE Year(order_date) = Year(@Parameter1) 
) 
+0

這給了我那些年來訂購的所有客戶,我想那些年沒有訂購的客戶。 –

+0

對不起,您的問題並不清楚。 – Ravenix