-4

在表格中获得了用户帐户列表,并附有 IP。

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

我确实有一个查询,但我失去了它

(我需要返回 ID、USERNAME 和 LAST_IP)- LAST_IP 也是存储 IP 以进行计数的位置

4

2 回答 2

0

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

SELECT ID, USERNAME, LAST_IP, count(*) as CNT from TABLE_NAME group by ID, USERNAME, LAST_IP HAVING count(*) > 5 ORDER BY CNT DESC

于 2013-03-26T22:08:22.777 回答
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
于 2013-03-26T22:18:24.407 回答