SQL:如果所有列都相等则计数记录

时间:2013-07-30 20:02:50

标签: sql sql-server count

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

现有记录:

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的产品都具有Active状态。

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

select   distinct OrderNo
from     Products p1
where    not exists
         (
         select  *
         from    Products p2
         where   p1.OrderNo = p2.OrderNo
                 and p2.Status = 'Active'
         )

Example at SQL Fiddle.

答案 2 :(得分:1)

SELECT COUNT(*)
FROM 
 (
   SELECT OrderNo
   FROM products
   GROUP BY OrderNo
   HAVING MIN(Status) = 'Active' AND MAX(Status) = 'Active'
 ) AS dt

答案 3 :(得分: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降序的索引应该会相当快。