2016-09-06 56 views
0

我有一個CustomerOrderCopy表,其中我想從特定時間範圍中選擇CustomerNameInvoiceDate。相同的結果不能在指定的其他時間範圍內。制定SQL查詢的問題

我該如何做到這一點?

SELECT CustomerName, InvoiceDate 
FROM CustomerOrderCopy 
WHERE (InvoiceDate BETWEEN '08.09.2016' AND '08.10.2016') 
AND (InvoiceDate NOT BETWEEN '08.11.2016' AND '09.06.2016') 
+0

AND NOT(InvoiceDate BETWEEN '08 .11.2016' 和09 .06.2016' )? –

+0

@JanDoggen我認爲Ronny想要排除也包含排除範圍內訂單的客戶 – JohnHC

+0

使用您的表結構和一些虛擬數據創建sql小提琴。 http://sqlfiddle.com/ – mikeb

回答

1
select C1.CustomerName, C1.InvoiceDate 
from CustomerOrderCopy C1 
left join CustomerOrderCopy C2 
    on C1.CustomerName = C2.CustomerName -- use ID if you have it 
    and C2.InvoiceDate between '08.11.2016' AND '09.06.2016' 
where C1.InvoiceDate between '08.09.2016' AND '08.10.2016' 

and C2.CustomerName is null -- This will exclude all those where there is a match 
3

嘗試使用NOT EXISTS:

SELECT CustomerName, InvoiceDate 
    FROM CustomerOrderCopy 
    WHERE (InvoiceDate BETWEEN '08.09.2016' AND '08.10.2016') 
    AND NOT EXISTS (SELECT 1 
         FROM CustomerOrderCopy as t2 
         WHERE t2.CustomerName=CustomerName 
         AND (InvoiceDate BETWEEN '08.11.2016' AND '09.06.2016') 
        );