SQL where 子句对表的影响?

asa*_*adz 0 syntax

我有 sql 查询作为

select sourceIP, sum(sourceBytes) 
from flows
group by sourceIP
order by sum(sourceBytes) desc
Run Code Online (Sandbox Code Playgroud)

这带来的结果(虚拟)为:-

sourceIp     SourceBytes
192.168.1.2  100
192.168.1.3  79
192.168.1.4  67
192.168.1.5  4
192.168.1.6  4
Run Code Online (Sandbox Code Playgroud)

现在,如果我将查询更改为

select sourceIP, sum(sourceBytes) 
from flows
where sourceBytes > 50
group by sourceIP
order by sum(sourceBytes) desc
Run Code Online (Sandbox Code Playgroud)

输出为

 sourceIp        SourceBytes
 192.168.1.2     150
 192.168.1.3     40
Run Code Online (Sandbox Code Playgroud)

我现在无法访问数据库,我无法拉/显示真实的表值,但这里我想用greaterthen 语句说明输出已更改。我是第二个查询的视图,我只想处理结果而不是将flows表中的所有值处理为更大范围的值,即 50。我想知道这两个查询的级别不同。谢谢。

Col*_*art 5

您正在执行 asum()这意味着您“丢失”了原始值——它们是聚合的。

通过应用where子句,您可以在聚合阶段之前过滤行。

我怀疑你想要的是一个having条款,比如:

select sourceIP, sum(sourceBytes) 
from flows
group by sourceIP
having sum(sourceBytes) > 50 
order by sum(sourceBytes) desc;
Run Code Online (Sandbox Code Playgroud)

Having就像一个where但应用于聚合结果。

请注意,您还可以使用子查询和 awhere代替,having如下所示:

select * from (
  select sourceIP, sum(sourceBytes) as sum_sourceBytes 
  from flows
  group by sourceIP
) a
where sum_sourceBytes > 50
order by sum_sourceBytes desc;
Run Code Online (Sandbox Code Playgroud)