SQL Server 2008 - 仅查找非活动记录

时间:2011-02-22 20:48:11

标签: sql-server sql-server-2008

我需要编写一个只显示非活动订单的查询。非活动订单被定义为没有活动订单商品的订单。

我有以下查询:

SELECT  Orders.OrderID, Orders.OrderDate
FROM    Orders INNER JOIN
        OrderItems ON Orders.OrderID = OrderItems.OrderID INNER JOIN
        Products ON OrderItems.ProductID = Products.ProductID INNER JOIN
        ProductSubCategories ON Products.ProductSubCategoryID = ProductSubCategories.ProductSubCategoryID INNER JOIN
        ProductCategories ON ProductSubCategories.ProductCategoryID = ProductCategories.ProductCategoryID
WHERE   (Orders.CustomerID = @CustomerID) AND (OrderItems.OrderItemStatusID = 2) AND (ProductSubCategories.ProductCategoryID = 1)
GROUP BY    Orders.OrderID, Orders.OrderDate

OrderItems.OrderItemStatusID = 2表示订单商品处于非活动状态。 OrderItems.OrderItemStatusID = 1表示订单商品处于活动状态。

问题在于查询不仅列出了所有非活动订单,还列出了同时包含非活动订单项和活动订单项的订单。

例如

订单123包含非活动和活动订单商品。它不应该出现在查询结果中,但确实如此。

订单234包含所有非活动订单商品。它显示正确。

如何排除订单123?

谢谢!

3 个答案:

答案 0 :(得分:3)

SELECT  Orders.OrderID, Orders.OrderDate
FROM    Orders INNER JOIN
        OrderItems ON Orders.OrderID = OrderItems.OrderID INNER JOIN
        Products ON OrderItems.ProductID = Products.ProductID INNER JOIN
        ProductSubCategories ON Products.ProductSubCategoryID = ProductSubCategories.ProductSubCategoryID INNER JOIN
        ProductCategories ON ProductSubCategories.ProductCategoryID = ProductCategories.ProductCategoryID
WHERE   (Orders.CustomerID = @CustomerID) AND (ProductSubCategories.ProductCategoryID = 1)
GROUP BY    Orders.OrderID, Orders.OrderDate
HAVING MIN(OrderItems.OrderItemStatusID) = 2

答案 1 :(得分:2)

编写一个子查询,查找包含活动项目的所有订单,然后使用该子查询识别不在该数据集中的所有订单。

E.g。

SELECT * FROM Orders
WHERE Orders.OrderID NOT IN (SELECT <query finding all orders with active items>)

答案 2 :(得分:0)

SELECT  Orders.OrderID, Orders.OrderDate
FROM    Orders
WHERE Orders.OrderID NOT IN
(select distinct o.OrderId 
 from Orders o
     left join OrderItems oi on o.OrderID = oi.OrderID
 where oi.OrderItemStatus != 2)