首页 > 解决方案 > 选择没有分配“事物”的用户数量

问题描述

我有一个显示我的问题的简化表
名称 动物
比尔狗
比尔猫
比尔鱼
约翰猫
约翰鱼
萨拉狗
萨拉猫
马克鱼

我想要没有狗的人数。我试过这个查询。

select count(distinct Name) from Table
where Animal <> 'Dog'



但它返回 4 而不是预期的 2。我做错了什么?

标签: sql

解决方案


使用not exists

select count(distinct t.name) as counts
from table t
where not exists (select 1 from table where name = t.name and animal = 'Dog');

对于您当前的查询,您正在根据animal名称过滤单个记录,这不会产生所需的结果,因为它应该与name列一起。


推荐阅读