Syntax

SQL where子句對錶的影響?

  • August 16, 2014

我有 sql 查詢作為

select sourceIP, sum(sourceBytes) 
from flows
group by sourceIP
order by sum(sourceBytes) desc

這帶來的結果(虛擬)為: -

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

現在,如果我將查詢更改為

select sourceIP, sum(sourceBytes) 
from flows
where sourceBytes > 50
group by sourceIP
order by sum(sourceBytes) desc

輸出是

sourceIp        SourceBytes
192.168.1.2     150
192.168.1.3     40

我現在無權訪問數據庫,我無法提取/顯示真實的表值,但是我想用greaterthen 語句說明輸出已更改。我對第二個查詢的看法是,我只想處理結果,而不是將flows表中的所有值處理為更大範圍的值,即 50。我想知道這兩個查詢的不同級別。謝謝。

你正在做sum()這意味著你“失去”了原始值——它們是聚合的。

通過應用子句,您可以在聚合階段之前where過濾行。

我懷疑您想要的是一個having子句,例如:

select sourceIP, sum(sourceBytes) 
from flows
group by sourceIP
having sum(sourceBytes) > 50 
order by sum(sourceBytes) desc;

Having就像 awhere但應用於聚合結果。

請注意,您還可以使用子查詢和 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;

引用自:https://dba.stackexchange.com/questions/73416