首页 > 解决方案 > 在 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。

标签: sqlamazon-web-servicesamazon-athena

解决方案


您可以使用select distinctandnot 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 idselect 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

推荐阅读