我有一张表格如下:
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的服务和至少一个其他服务。
谢谢!
答案 0 :(得分:4)
在MS SQL中:
select count(*)
from UserService
where
ServiceId = 3 and
UserId in (select UserId from UserService where ServiceId != 3)
答案 1 :(得分:2)
编辑回复评论:
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