1

假设我有这张桌子:

    | 身份证 | 身份服务 |
    | 1 | 5 |
    | 1 | 10 |
    | 2 | 5 |
    | 2 | 15 |
    | 3 | 5 |
    | 3 | 20 |
    | 4 | 5 |
    | 4 | 25 |
    
我希望能够选择存在产品 5 的所有客户(ID)以及至少一个其他产品(10、15、20、25)。

我可以通过查询对其中一种组合执行此操作:

SELECT ID FROM table WHERE idService IN (5,10) GROUP BY ID HAVING COUNT(DISTINCT idService) = 2

但是,如果我在此查询中添加其他条件,我将获得至少拥有两种产品的所有客户,无论是 5 和 10 还是 10 和 20 都没关系。

SELECT ID FROM table WHERE idService IN (5,10) OR idService IN (5,15) OR idService IN (5,20) OR idService IN (5,25) GROUP BY ID HAVING COUNT(DISTINCT idService) = 2

我想知道是否可以更改 IN 子句或替换它们以仅获取具有四种有效组合之一的客户端。

编辑:

我已经能够使用子查询使查询工作。

SELECT ID FROM table WHERE ID IN ( SELECT ID FROM table WHERE idService =5) AND ( idService =10 OR idService =15 OR idService =20 OR idService =25 ) GROUP BY idSPOrder

4

3 回答 3

3
select distinct ID from table t1
where (select count(*) from table where ID = t1.ID group by ID) >=2
and (select count(*) from table where Idservice = 5 and ID = t1.ID group by ID) > 0
于 2013-09-26T16:27:40.873 回答
1
select Id 
from Table T
where exists (select 1 from Table where Id = T.Id AND idService = 5)
group by Id
having count(*) >= 2
于 2013-09-26T15:23:35.197 回答
0
select table.id from table, 
(select id from table where idservice != 5 group by id)t 
where idservice = 5 and table.id = t.id
于 2013-09-26T15:27:35.720 回答