SQL Server 2008 - 与两个条件匹配的查询

时间:2011-02-28 14:25:20

标签: sql-server sql-server-2008

我正在尝试找到剩下几周同时拥有1和4的客户(CustomerID)。我正在使用以下查询:

SELECT  o.CustomerID, oi.RemainingWeeks
FROM    Orders o INNER JOIN
        OrderItems oi ON o.OrderID = oi.OrderID 
WHERE   (oi.OrderItemStatusID = 1) AND (oi.RemainingWeeks IN (1, 4)) 
ORDER BY o.CustomerID, oi.RemainingWeeks

这可以找到剩下几周或4周的客户,但不包含两周的客户。我是否需要修改我的联接才能使其正常工作?

谢谢!

2 个答案:

答案 0 :(得分:6)

要意识到的关键是,永远不会是来自OrderItems的RemainingWeek等于1和4的单行。所以你需要以某种方式涉及多行。您可以通过聚合实现此目的,或者仅执行第二次连接:

SELECT  o.CustomerID, oi1.RemainingWeeks,oi2.RemainingWeeks
FROM    Orders o INNER JOIN
        OrderItems oi1 ON o.OrderID = oi1.OrderID INNER JOIN
        OrderItems oi2 ON o.OrderID = oi2.OrderID
WHERE   (oi1.OrderItemStatusID = 1) AND (oi1.RemainingWeeks =1) AND
        (oi2.OrderItemStatusID = 1) AND (oi2.RemainingWeeks =4) 
ORDER BY
     o.CustomerID, oi1.RemainingWeeks,oi2.RemainingWeeks

答案 1 :(得分:3)

这是一个relational division问题。通过聚合来解决它的方法是

SELECT  o.CustomerID
FROM    Orders o INNER JOIN
        OrderItems oi ON o.OrderID = oi.OrderID 
WHERE   (oi.OrderItemStatusID = 1) AND (oi.RemainingWeeks IN (1, 4)) 
GROUP BY o.CustomerID
HAVING COUNT(DISTINCT oi.RemainingWeeks) = 2
ORDER BY o.CustomerID