开发者

SQL Count number of values given compound condition on row

开发者 https://www.devze.com 2023-03-09 08:23 出处:网络
I have a table as follows: User IDSe开发者_如何学运维rvice 12 13 21 23 35 33 43 52 How could I construct a query where I would count all the user ids that have a service of 3 and at least one othe

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

精彩评论

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