计算在另一个字段中都具有相同值的维项目

时间:2019-07-10 23:45:02

标签: sql

我有一个如下表: business_id,employee_id和状态(“活动”或“非活动”

example table

我想计算其所有员工均处于“活跃”状态的公司数量。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

这是一种方法:

select count(distinct business_id)
from t
where not exists (select 1
                  from t t2
                  where t2.business_id = t.business_id and
                        t2.status <> 'active'
                 );

或者,两个聚合级别:

select count(*)
from (select business_id
      from t
      group by business_id
      having min(status) = max(status) and min(status) = 'active'
     ) b;