在Oracle 11g中,我只有一张桌子,宠物。宠物有两列,所有者和类型。桌子上唯一的宠物是狗、猫和鱼。
有些主人有两只宠物。
我想选择所有拥有猫和狗的主人。我怎么能这么做?
发布于 2017-11-30 19:44:18
做这件事有很多不同的方法,这里有一种:
select owner from pets where type = 'CAT'
intersect
select owner from pets where type = 'DOG'INTERSECT产生了一组猫和狗的不同主人。
发布于 2017-11-30 20:03:05
你可以用GROUP BY和HAVING
SELECT t.owner
FROM tab t
WHERE t.type IN ('dog', 'cat')
GROUP BY t.owner
HAVING COUNT(DISTINCT t.type) = 2;发布于 2017-11-30 19:58:18
想象一张这样的桌子:
|owner || type|
-----------------
|own1 | dog |
|own1 | cat |
|own2 | dog |
|own3 | dog |
|own3 | fish|你可以试试这样的方法:
select o.cat_and_dog_owner
from(
select t.owner as cat_and_dog_owner, sum(case when t.type = 'dog' then 1 else 0 end) as dog_cnt, sum(case when t.type = 'cat' then 1 else 0 end) as cat_cnt
from table t
where t.type in ('dog', 'cat')
group by t.owner
having (sum(case when t.type = 'dog' then 1 else 0 end) > 0) and (sum(case when t.type = 'cat' then 1 else 0 end) > 0)
) o基本上,你只想选择猫和狗的记录。我们结合使用sum和case来计算按主人分组的狗和猫的数量。最后,我们使用having子句检查,以确保只获得两列中的计数大于0的记录。
https://stackoverflow.com/questions/47581378
复制相似问题