开发者

SQL Count number of values given compound condition on row

I have a table as follows:


User ID  Se开发者_如何学运维rvice
1        2
1        3
2        1
2        3
3        5
3        3
4        3
5        2

How could I construct a query where I would count all the user ids that have a service of 3 and at least one other service?

In the above table, the query I'm interested in would return 3 because user ids 1, 2 and 3 have service of 3 and at least one other service.

Thanks!


In MS SQL:

select count(*)
from UserService
where 
    ServiceId = 3 and
    UserId in (select UserId from UserService where ServiceId != 3)


EDIT In response to comments:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜