SQL结果表满足两个条件

时间:2014-03-31 16:42:44

标签: sql

我希望我能够很好地解释这一点。

说我有这张桌子:

Owner
+--------+--------+
| Name   | Type   |
+--------+--------+
| Bob    | Cat    |
| Bob    | Dog    |
| Bob    | Cow    |
| Tim    | Dog    | 
| Tim    | Cat    |
| Ted    | Cat    | 
| Joe    | Dog    |
| Joe    | Cat    |
| Joe    | Sheep  |
+--------+--------+

我试图找到所有拥有所有动物的人(所以猫和狗)。这意味着乔和鲍勃会满足这个,但不是泰德,因为他只有一种动物蒂姆已经

我如何获得这个结果?

所以我有一张包含蒂姆拥有的所有类型的表:

SELECT Type FROM Owner WHERE Name= 'Tim';

我如何才能获得它,只有那些同时具有两种类型的人才能从所有者列表中选出?

任何指导都将不胜感激,提前谢谢。

3 个答案:

答案 0 :(得分:0)

select name
from owner
where type in (select distinct type from owner where name = 'tim')
group by name
having count(distinct type) = (select count(distinct type) from owner where name = 'tim')

答案 1 :(得分:0)

如果你只是想让所有拥有更多动物的人而不是蒂姆has那么你可以像

那样做
select Name from owners
group by Name
having count(distinct [Type]) > (select count(distinct type) from owners
where Name='tim') 

答案 2 :(得分:0)

我认为这是joingroup by问题。将Tim的记录加入所有其他所有者,但在type字段。然后进行聚合并仅保留所有type匹配的记录:

select o.name
from owner otim left join
     owner o
     on o.type = tim.type and o.name <> 'Tim' and otim.name = 'Tim'
group by o.name
having min(case when o.type is null then 0 else 1 end) = 0;

请注意,即使表中允许重复的type值,也可以使用此功能。