选择包含多个项目的所有订单并检查所有项目状态

时间:2012-12-27 09:37:54

标签: sql tsql sql-server-2005

我有两张桌子:

订单:

Id   |  Status
-----+--------
 1   |      OK
 2   | WAITING
 3   | WAITING
 4   |      OK
 5   |      OK
 6   |      OK

和Order_details:

Id   |  Order_Id  |  Status
-----+------------+--------
 1   |         1  |      S1
 2   |         1  |      S1
 3   |         2  |      S1
 4   |         4  |      S2
 5   |         4  |      S2
 6   |         4  |      S3
 7   |         5  |      S1
 8   |         5  |      S1

我需要做的是选择所有包含多个Order_detail的订单,订单状态必须为'OK'且每个order_detail 必须在(S1,S2)中具有状态

我做过这样的事情:

SELECT O.Id FROM Orders O 
            JOIN Order_details OD 
                ON O.Id=OD.Order_Id
WHERE O.Status='OK' AND OD.Status IN ('S1','S2')
GROUP BY O.Id
HAVING count(DISTINCT OD.Id)>1

但是这会返回所有具有多个Order_details会议条件的订单。

我确信这部分很好:

SELECT O.Id FROM Orders O 
            JOIN Order_details OD 
                ON O.Id=OD.Order_Id
WHERE O.Status='OK'
GROUP BY O.Id
HAVING count(DISTINCT OD.Id)>1

但我必须检查上述订单的每个Order_detail是否都有状态IN(S1,S2)。

因此,如果Order有2个详细信息,其中一个有status = S1和第二个S3,则应跳过此顺序。

2 个答案:

答案 0 :(得分:2)

SELECT O.Id 
FROM Orders O 
JOIN Order_details OD ON O.Id=OD.Order_Id
WHERE O.Status='OK'
GROUP BY O.Id
HAVING count(DISTINCT OD.Id)>1
AND SUM(CASE WHEN OD.Status NOT IN ('S1','S2') 
             THEN 1 
             ELSE 0 
        END) = 0

答案 1 :(得分:1)

select O.id
from orders O inner join order_details OD
on O.Id=OD.Order_Id and O.Status='OK' AND OD.Status IN ('S1','S2')
GROUP BY O.Id
HAVING count(DISTINCT OD.Id)>1