制定SQL查询的问题

时间:2016-09-06 12:29:13

标签: sql sql-server select

我有一个CustomerOrderCopy表格,我想从中选择特定时间范围内的CustomerNameInvoiceDate。相同的结果不能在指定的其他时间范围内。

我该如何做到这一点?

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')

2 个答案:

答案 0 :(得分: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' )
                    ); 

答案 1 :(得分: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