select 登录用户号,有效次数=sum(case when IP>5 then 5 else IP end)
from (select 登录用户号,服务器地址,IP=count(1) from 表 where 登录用户号 is not null group by 登录用户号,服务器地址) AS a
group by 登录用户号
order by 有效次数 desc

解决方案 »

  1.   

    --原始数据:@T
    declare @T table(服务器地址 varchar(11), 登录用户号 int)
    insert @T
    select '192.168.0.1',10001 union all
    select '192.168.0.1',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10002 union all
    select '192.168.0.2',10002 union all
    select '192.168.0.3',10002 union all
    select '192.168.0.3',null union all
    select '192.168.0.3',null union all
    select '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 a
    group by 登录用户号
    order by 有效次数 desc
    /*
    登录用户号 有效次数
    10001 7
    10002 4
    */select 排名=identity(int,1,1),登录用户号,有效次数=sum(case when IP>5 then 5 else IP end)
    into #Result
    from (select 登录用户号,服务器地址,IP=count(1) from @T where 登录用户号 is not null group by 登录用户号,服务器地址) AS a
    group by 登录用户号
    order by 有效次数 descselect * from #Result
    /*
    排名 登录用户号 有效次数
    1 10001 7
    2 10002 4
    */--删除测试
    drop table #Result
      

  2.   

    方法2
    --原始数据:@T
    declare @T table(服务器地址 varchar(11), 登录用户号 int)
    insert @T
    select '192.168.0.1',10001 union all
    select '192.168.0.1',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10001 union all
    select '192.168.0.2',10002 union all
    select '192.168.0.2',10002 union all
    select '192.168.0.3',10002 union all
    select '192.168.0.3',null union all
    select '192.168.0.3',null union all
    select '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 7
    10002 4
    */--删除测试
    drop table #Temp
      

  3.   

    非常感谢Limpire的解答,我参考了您在2楼给出的方式,完美解决了这个问题。再次感谢。再追加一个小问题:这论坛加分怎么加?:) 我点加分它说发帖还不够5天…… :P