2013-03-26 96 views
-4

獲取表中的用戶帳戶列表,並附帶IP地址。計算表中字段重複次數超過5次的行

我需要運行一個查詢,只顯示具有超過5個相同IP的行。

我有一個查詢,但我已經失去了它

(我需要ID,用戶名和LAST_IP返回) - LAST_IP也是其中的IP存儲做計數

+2

您正在尋找'HAVING COUNT(someField)> 5' http://stackoverflow.com/a/3710501/1618257 – 2013-03-26 22:03:09

+0

您能提供一個迄今爲止嘗試過的例子,沒有人會做爲您工作,如果您的代碼/ SQL無法正常工作,他們將幫助解決問題。 – llanato 2013-03-26 22:05:21

+0

雖然我無法找到任何東西,所以即時要求粗略的幫助。 – 2013-03-26 22:14:53

回答

0

這裏是一個例子:

declare @table table (user_id int identity(1, 1), user_name varchar(100), last_ip varchar(50)) 

insert into @table (user_name, last_ip) values ('joe moe', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('xyz', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('dummy', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('harry potter', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('he who should not be named', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('times square', '192.168.0.XX') 
insert into @table (user_name, last_ip) values ('user1', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('user2', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('user3', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('user4', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('user5', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('user6', '192.168.0.YY') 
insert into @table (user_name, last_ip) values ('tom dick harry', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('peter pan', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('humpty dumpty', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('red riding hood', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('tintin', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('mickey mouse', '192.168.0.ZZ') 
insert into @table (user_name, last_ip) values ('only user', '192.168.0.AA') 

select a.* from @table a 
inner join 
(
    select last_ip, count(*) as cnt from @table 
    group by last_ip 
    having count(*) > 5 
) allCounts 
on a.last_ip = allCounts.last_ip 
0

這聽起來像你需要做的是這樣的:

SELECT ID,USERNAME,LAST_IP,通過ID,USERNAME COUNT(*)作爲CNT從TABLE_NAME組,LAST_IP HAVING COUNT(*)> 5 ORDER BY CNT DESC

+0

我試過這個,但是它沒有統計IP地址 – 2013-03-26 22:13:05