【问题标题】:Count rows in table where field is duplicated more than 5 times [closed]计算表中字段重复超过 5 次的行数[关闭]
【发布时间】:2013-03-26 22:00:00
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你在找HAVING COUNT(someField)>5stackoverflow.com/a/3710501/1618257
  • 您能否提供一个到目前为止您尝试过的示例,没有人会为您工作,如果您的代码/SQL 无法正常工作,他们会帮助解决问题。跨度>
  • 我在上面找不到任何东西,所以我寻求粗略的帮助。

标签: sql count


【解决方案1】:

这是一个例子:

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

【讨论】:

    【解决方案2】:

    听起来你需要这样做:

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

    【讨论】:

    • 我试过这个,但它不计算IP地址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2021-11-24
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多