sql - 选择没有分配“事物”的用户数量
问题描述
我有一个显示我的问题的简化表
名称 动物
比尔狗
比尔猫
比尔鱼
约翰猫
约翰鱼
萨拉狗
萨拉猫
马克鱼
我想要没有狗的人数。我试过这个查询。
select count(distinct Name) from Table
where Animal <> 'Dog'
但它返回 4 而不是预期的 2。我做错了什么?
解决方案
使用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
列一起。
推荐阅读
- r - 在 R 中选择单独的对象并将它们绑定到一个数据帧
- mockito - 可选的模拟匹配器
和地图 - c# - 无法使用 System.Data.SqlClient 4.4.3 和主机名连接到 sql 数据库,但 ip 有效
- ajax - Prestashop Ajax 值到模块类
- c# - 在 ADF .NET SDK 中向数据流添加和元素
- sql - 如何在 SQL 中将 varchar unixcode 转换为时间戳
- toolbar - 使用 pywinauto 更改工具栏中的文本
- java - Java EE Entity Manager 不会从 Callable 线程更新实体
- flutter - Flutter Provider,使用子小部件更新列表
- php - 在 WordPress MySQL 查询中切换布尔值不起作用