【问题标题】:SQL Query to Find Unique Values After Where and GroupBy在 Where 和 GroupBy 之后查找唯一值的 SQL 查询
【发布时间】:2020-05-01 18:32:06
【问题描述】:

使用 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。

【问题讨论】:

标签: sql amazon-web-services amazon-athena


【解决方案1】:

您可以使用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')

如果你想要 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

【讨论】:

  • 如何为多个软件应用程序执行此操作?
  • @mbspark:只需使用更多not exists 条件扩展查询即可。
  • @mbspark: 否 - where not exists (select 1 from mytable t1 where t1.id = t.id and t1.name = 'Notepad') and not exists (select 1 from mytable t1 where t1.id = t.id and t1.name = 'Powerpoint')
【解决方案2】:

我正在寻找可以告诉我有多少服务器(在本例中)没有安装“记事本”的 SQL 查询。

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

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 表。然后你会这样做:

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.*

【讨论】:

  • 我实际上想显示 ID,以便以后可以使用它们进行进一步处理,而不仅仅是计数。我会更好地编辑和解释。
  • @mbspark 。 . .您的问题明确要求 count 这就是我回答的原因。我也修改了列表的问题。
  • 你是 100% 正确的。我编辑了我想要的结果。我的错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多