簡體   English   中英

單個查詢以打印計數大於10的所有行

[英]single query to print all the rows whose count is greater than 10

我有一個名為Table1的表,其定義如下。

Id  int False   
Source  nvarchar(MAX)   True    
Dest    nvarchar(MAX)   True    
Port    nvarchar(MAX)   True    
DgmLen  nvarchar(MAX)   True    
Flags   nvarchar(MAX)   True    
Payload nvarchar(MAX)   True    

現在,我要打印此表中“源”計數大於10的所有行。

首先,我使用此查詢來獲取表中的源計數:

Select Source,count(*) t_count from Table1 group by Source

並且已獲取以下數據:

Source            t_count
2-170.125.32.3  1
2-172.125.32.10 1
2-190.125.32.10 11
2-190.125.32.3  1
2-192.125.32.10 1
2-192.125.32.3  6

現在,我要打印所有具有“源= 2-190.125.32.10”的行,因為其t_count大於10。

如何在單個查詢中編寫此代碼。

具有“源= 2-190.125.32.10”

這就是關鍵字: having

Select Source,count(*) t_count from Table1 group by Source HAVING t_count > 10

順便說一句:如果您要按Soruce分組-總是有一個與特定來源相匹配的結果行​​-這就是分組的重點。

如果我正確地理解了你,那么:-

select * from Table1 where Source in
(
Select Source from Table1 group by Source having count(*) > 10
)

這將返回Table1所有具有Source列值出現超過10次的行。

編輯:-

select * from Table1 t1 join
(Select Source, Dest from Table1 group by Source, Dest having count(*) > 10) t2
on t1.Source = t2.Source and t1.Dest = t2.Dest

在此,表t2返回出現了10次以上的Source, Dest組合,並將其與基本表Table1連接起來。

您的單個查詢應如下所示

Select Source,count(*) t_count from Table1 group by Source HAVING t_count > 10

做出類似的例子

Select 
s.Source,
s.Dest,
s.Port,
s.DgmLen,
s.Flags,
s.Payload
from Table1 s
join
(
  select 
  source,
  count(*) as tot
  from Table1
  group by source
  having tot > 10
)s1
on s1.source = s.source

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM