0

我只需要计算所有产品状态为Active的那些订单号。

现有记录:

OrderNo     ProductID     Status
1           1             Active
1           2             Active
1           3             Active
2           1             Inactive
2           2             Inactive
3           3             Active
4           1             Inactive
4           3             Active

输出:

Completed
2

注意:OrderNo 1 和 3 的产品都处于活动状态。

4

4 回答 4

2

获取具有活动数量的总订单

SELECT COUNT(*) FROM 
(SELECT * FROM products WHERE OrderNo NOT IN (SELECT * FROM products WHERE Status = 'Inactive' GROUP BY OrderNo)) as tmp_b; OrderNo

仅获取订单号

SELECT OrderNo FROM 
(SELECT * FROM products WHERE OrderNo NOT IN (SELECT * FROM products WHERE Status = 'Inactive' GROUP BY OrderNo)) as tmp_b;
于 2013-07-30T20:03:44.947 回答
1
select   distinct OrderNo
from     Products p1
where    not exists
         (
         select  *
         from    Products p2
         where   p1.OrderNo = p2.OrderNo
                 and p2.Status = 'Active'
         )

SQL Fiddle 的示例。

于 2013-07-30T20:05:13.447 回答
1
SELECT COUNT(*)
FROM 
 (
   SELECT OrderNo
   FROM products
   GROUP BY OrderNo
   HAVING MIN(Status) = 'Active' AND MAX(Status) = 'Active'
 ) AS dt
于 2013-07-30T21:07:22.237 回答
0

假设ActiveInactive是唯一的选择:

select Count( distinct OrderNo )
  from Products as OuterP
  where not exists ( select 42 from Products where OrderNo = OuterP.OrderNo and Status = 'Inactive' )

关于OrderNo升序/Status降序的索引应该使这相当快。

于 2013-07-30T20:15:25.107 回答