SQL 查询以在 Where 和 GroupBy 之后查找唯一值

SQL Query to Find Unique Values After Where and GroupBy

使用 AWS Athena 查询 aws_application table.

Table有如下内容

ID | Name 
server1  | Word 
server1  | Excel
server2  | Word 
server2  | Excel
server3  | Word 
server3  | Excel
server3  | Notepad 

我正在寻找 SQL 可以列出未安装 "Notepad" 的服务器 ID(在此示例中)的查询。结果应该显示。

ID
server1
server2

我是新手,到目前为止我只能显示哪个服务器有记事本。我以为我可以以某种方式将 table 加入自身并减去以尝试获取唯一 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 台服务器的唯一计数。我想要 return 数字 8。

当然这里有数千行,因为 table 中的每一行代表安装在盒子上的不同应用程序 exe。

I'm looking for SQL Query that can tell me how many servers (in this example) DON'T have "Notepad" installed.

您可以使用两个聚合级别:

select count(*)
from (select id, sum(case when name = 'Notepad' then 1 else 0 end) as num_notepad
      from aws_application a
      group by id
     ) s
where num_notepad = 0;

如果您想要列表而不是计数:

select id, 
from aws_application a
group by id
having sum(case when name = 'Notepad' then 1 else 0 end) = 0;

不过,更典型的情况是,您会有一个 servers table。那么你会做:

select count(*)
from servers s
where not exists (select 1
                  from aws_application a
                  where a.userid = s.userid and
                        a.name = 'Notepad'
                 );

或者对于列表,请改用 select s.*

您可以使用 select distinctnot exists 进行过滤:

select distinct id
from mytable t
where not exists (select 1 from mytable t1 where t1.id = t.id and t1.name = 'Notepad')

如果你想要ids的数量,那么你可以把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