按特定日期范围获取客户

时间:2014-03-17 20:35:22

标签: sql-server tsql sql-server-2012

我需要查询在两个日期之间下订单的客户,但他们之前没有订购,此后也没有订购......

这是我的查询,我认为结果是正确的,但我想知道是否有更简洁的方法来获得所需的查询。

SELECT c.customerno 
from Customer c 
WHERE c.CustomerID in
                  (SELECT t.CustomerID 
                  from [Transaction] t 
                  WHERE 
                    (t.StartSaleTime  between '2/25/2013' And '04/03/2013') 
                  or t.StartSaleTime  between '2/25/2014' And '04/03/2014')
AND c.CustomerID not in 
                     (SELECT t.CustomerID 
                     from [Transaction] t 
                     WHERE t.StartSaleTime < '2/25/2013')
AND c.CustomerID not in 
                     (SELECT t.CustomerID 
                     from [Transaction] t 
                     WHERE t.StartSaleTime > '04/03/2013')

编辑:请求被修改为还包括其他日期范围,这使得它更复杂......

2 个答案:

答案 0 :(得分:2)

SELECT c.customerno 
from Customer c INNER JOIN [Transaction] t
ON C.CustomerID  = t.CustomerID 
WHERE t.StartSaleTime >= '2/25/2013' 
AND   t.StartSaleTime <= '04/03/2013'
AND NOT EXISTS
             (SELECT 1 
              from [Transaction]  
              WHERE StartSaleTime < '2/25/2013'
              AND CustomerID = C.CustomerID)
AND NOT EXISTS
             (SELECT 1 
              from [Transaction]  
              WHERE StartSaleTime > '04/03/2013'
              AND CustomerID = C.CustomerID)

同时避免将BETWEEN运算符与日期一起使用。之所以阅读Aaron Bertrand的这篇文章What do BETWEEN and the devil have in common?

答案 1 :(得分:1)

查询似乎正确,但第二个和第三个子查询可以合并为一个。此外,我不知道StartSaleTime的确切数据类型,但如果它是DATETIME,那么您应该避免使用BETWEEN。无论如何,你可以这样做:

SELECT c.customerno 
FROM Customer c 
WHERE EXISTS(SELECT 1 FROM [Transaction]
             WHERE StartSaleTime BETWEEN '2/25/2013' AND '04/03/2013'
             AND CustomerID = c.CustomerID)
AND NOT EXISTS( SELECT 1 FROM [Transaction]
                WHERE CustomerID = c.CustomerID
                AND (StartSaleTime < '2/25/2013' 
                  OR StartSaleTime > '04/03/2013'))