我需要编写一个仅显示非活动订单的查询。非活动订单被定义为没有活动订单项目的订单。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号订单?
谢谢!
方便快捷。谢谢! – Mike 2011-02-22 21:27:57
@Mike,这不是最有效的查询,但由于它包含@CustomerID,因此假设单个客户没有数以百万计的订单并且CustomerID列上有索引,这应该没有关系。 – 2011-02-22 21:38:12