对表中的行进行计数,其中字段重复次数超过5次

时间:2013-03-26 22:00:01

标签: sql count

在表格中列出了用户帐户,随附的是IP。

我需要运行一个只显示具有5个以上相同IP的行的查询。

我确实有查询,但我已经失去了它

(我需要ID,USERNAME和LAST_IP返回) - LAST_IP也是存储IP以进行计数的地方

2 个答案:

答案 0 :(得分:0)

听起来你需要做这样的事情:

SELECT ID,USERNAME,LAST_IP,count(*)作为来自TABLE_NAME组的CNT ID,USERNAME,LAST_IP HAVING count(*)> 5 CNT DESC订购

答案 1 :(得分: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