SQL客户订单列表

时间:2016-10-21 14:03:55

标签: sql-server

我正在努力获取1月份订购的客户名单。二月,但不是三月

SELECT distinct C.CustID, FirstName + ', ' + LastName AS CustomerName, OrderDate
FROM Customers C JOIN Orders O ON 
        C.CustID = O.CustID
WHERE C.CustID in
        (select CustID
        from Customers
        where month(OrderDate) >= 01)
    and
        C.CustID in
        (select CustID
        from Customers
        where month(OrderDate) <= 02)
    and
        C.CustID IN 
        (select CustID
        from Customers
        where month(OrderDate) != 03);

3 个答案:

答案 0 :(得分:0)

查找3月份订单并使用NOT IN运算符代替IN的客户

SELECT distinct C.CustID, FirstName + ', ' + LastName AS CustomerName, OrderDate
FROM Customers C JOIN Orders O ON 
        C.CustID = O.CustID
WHERE C.CustID in
        (select CustID
        from ORders
        where month(OrderDate) BETWEEN 1 AND 2)    
    AND C.CustID NOT IN 
        (select CustID
        from ORders
        where month(OrderDate) 03);

我还将条件中的前两个更改为一个,这样可以更快地使用它。

另外,正如@Matthew所指出的,您的CustID和OrderDate字段可能在您的Order表上,因此在子查询中使用它会更好一些。

答案 1 :(得分:0)

顺便说一下:

SELECT C.CustID, C.FirstName + ', ' + C.LastName AS CustomerName, O1.OrderDate
FROM Customers C
INNER JOIN (
    SELECT CustID FROM Orders WHERE month(OrderDate) IN (1,2)
) O1 ON C.CustID=O1.CustID
LEFT JOIN (
    SELECT CustID FROM Orders WHERE month(OrderDate) IN (3)
) O2 ON C.CustID=O2.CustID
WHERE O2.CustID IS NULL
GROUP BY C.CustID, C.FirstName, C.LastName, O1.OrderDate

答案 2 :(得分:0)

SELECT C.CustID, C.FirstName + ', ' + C.LastName AS CustomerName, O1.OrderDate
FROM Customers C
LEFT OUTER JOIN 
          (SELECT CustID FROM Orders WHERE month(OrderDate) IN (3) ) O ON 
    O. CustID = C.CustID
WHERE month(C.OrderDate) IN (1,2)
AND O.CustID IS NULL