sql - 在 Where 和 GroupBy 之后查找唯一值的 SQL 查询
问题描述
使用 AWS Athena 查询 aws_application 表。
表有如下内容
ID | Name
server1 | Word
server1 | Excel
server2 | Word
server2 | Excel
server3 | Word
server3 | Excel
server3 | Notepad
我正在寻找可以列出未安装“记事本”的服务器 ID(在此示例中)的 SQL 查询。结果应该显示。
ID
server1
server2
我是新手,到目前为止我只能显示哪个服务器有记事本。我想我可以以某种方式将表连接到自身并减去以尝试获取唯一 ID。
上面的例子是通用的,但更容易解释。在我的确切我可以运行以下
select distinct resourceid
from aws_application
where name = 'Excel'
or name = 'Word'
group by resourceid
并获得总共108台服务器。
如果我跑
select distinct resourceid
from aws_application
group by resourceid
我得到了 116 台服务器的唯一计数。我想返回数字 8。
当然,这里有数千行,因为表格中的每一行代表盒子上安装的不同应用程序 exe。
解决方案
您可以使用select distinct
andnot exists
进行过滤:
select distinct id
from mytable t
where not exists (select 1 from mytable t1 where t1.id = t.id and t1.name = 'Notepad')
如果您想要 id 的计数,则可以更改select distinct id
为select count(distinct id)
. 如果您想要整个记录,您可以将其更改为select t.*
另一种选择是使用反left join
:
select distinct t.id
from mytable t
left join mytable t1 on t1.id = t.id and t1.name = 'Notepad'
where t1.id is null
推荐阅读
- docker - docker运行报错:layer不存在
- javascript - 语法错误:使用“fast-image-zoom”时无法在模块外使用导入语句
- c# - 如何在调试时找出 wcf 检查的所有端点
- flutter - 无法打开设置文件的设置通用类缓存
- python - 使用 pandas 将 Json 转换为 DataFrame
- python - 如何在 selenium python 中保存来自 whatsapp 的站点数据(如 cookie)
- javascript - 替换存储在变量中的img的src
- apple-watch - 在没有 xcode 的情况下为苹果 watc 创建一个应用程序
- go - 如何使用 Go 在 Elasticsearch 查询中放置格式说明符?
- c# - 将 IConfiguration 传递给静态类的好方法?