如何在SQL里进行有条件的重复记录查询并统计总数的
目前是这样一个情况。
表格式如下:
服务器地址 登录用户号
192.168.0.1 10001
192.168.0.1 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10001
192.168.0.2 10002
192.168.0.2 10002
192.168.0.3 10002
192.168.0.3 null
192.168.0.3 null
192.168.0.3 10002
…… (还有很多条)
要求是:
1.统计并显示用户登录出现次数排名。
2.登录相同的服务器最多只计算5次,多的登录记录无效。
3.忽略掉“登录用户号”是null(空白)的记录。
预期出现的结果是:
排名 登录用户号 有效次数
1 10001 7 (虽然记录有10条,但因上面第二条规则缘故,有4条记录忽略)
2 10002 4
……
这个问题对我这菜鸟实在是太难了。我会统计总记录中,每个用户号出现多少次和简单按出现次数排名,但是不会统计“相同的服务器最多只计算5次,多的登录记录无效”这种前提条件的的。求教于各位前辈,请问应该如何解决?
[解决办法]
select 登录用户号,有效次数=sum(case when IP>5rchar
[解决办法]
--原始数据:@Tdeclare @T table(服务器地址 varchar(11), 登录用户号 int)insert @Tselect '192.168.0.1',10001 union allselect '192.168.0.1',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10002 union allselect '192.168.0.2',10002 union allselect '192.168.0.3',10002 union allselect '192.168.0.3',null union allselect '192.168.0.3',null union allselect '192.168.0.3',10002select 登录用户号,有效次数=sum(case when IP>5 then 5 else IP end)from (select 登录用户号,服务器地址,IP=count(1) from @T where 登录用户号 is not null group by 登录用户号,服务器地址) AS agroup by 登录用户号order by 有效次数 desc/*登录用户号 有效次数10001 710002 4*/select 排名=identity(int,1,1),登录用户号,有效次数=sum(case when IP>5 then 5 else IP end)into #Resultfrom (select 登录用户号,服务器地址,IP=count(1) from @T where 登录用户号 is not null group by 登录用户号,服务器地址) AS agroup by 登录用户号order by 有效次数 descselect * from #Result/*排名 登录用户号 有效次数1 10001 72 10002 4*/--删除测试drop table #Result
[解决办法]
方法2
--原始数据:@Tdeclare @T table(服务器地址 varchar(11), 登录用户号 int)insert @Tselect '192.168.0.1',10001 union allselect '192.168.0.1',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10001 union allselect '192.168.0.2',10002 union allselect '192.168.0.2',10002 union allselect '192.168.0.3',10002 union allselect '192.168.0.3',null union allselect '192.168.0.3',null union allselect '192.168.0.3',10002--如果原始数据表有主键或唯一性列,不需要临时表:select ID=identity(int,1,1),* into #Temp from @T where 登录用户号 is not nullselect 登录用户号,有效次数=count(*)from #Temp a where ID in (select top 5 ID from #Temp where 服务器地址=a.服务器地址 and 登录用户号=a.登录用户号)group by 登录用户号order by 有效次数 desc/*登录用户号 有效次数10001 710002 4*/--删除测试drop table #Temp