SQL计数行上给定复合条件的值的数量

问题描述

| 我有一张桌子,如下所示:
User ID  Service
1        2
1        3
2        1
2        3
3        5
3        3
4        3
5        2
我该如何构造一个查询,在该查询中我将计算服务3和至少一个其他服务的所有用户ID? 在上表中,我感兴趣的查询将返回3,因为用户ID 1、2和3的服务为3,并且至少还有一个其他服务。 谢谢!     

解决方法

        在MS SQL中:
select count(*)
from UserService
where 
    ServiceId = 3 and
    UserId in (select UserId from UserService where ServiceId != 3)
    ,        编辑回应评论:
select count(*) from (

select userId
  from theTable
 group by userId
having sum(case when service = 3 then 1 else 0 end) > 0
   and sum(case when service <>3 then 1 else 0 end) > 0

) x