tableA:
--------------------
id      number
name    varchar2
reason  varchar2
level   int
原始数据
------------------------------
id     name       reason     level
111   '管理员1'   '登陆'       1
112   '管理员1'   '重复登陆'   2
113   '管理员1'   '重复登陆'   2
114   '管理员1'   '退出'       4
115   '管理员2'   '登陆'       1
115   '管理员2'   '修改'       1
200   '管理员2'   '注销'       1
201   '管理员3'   '删除'       2
202   '管理员4'   '登陆'       1
204   '管理员4'   '登陆'       1
204   '管理员4'   '退出'       4
..........结果:查出name出现次数最多的前三个,以name,level分组,统计各个level的次数,即下面结果name       level  次数
'管理员1'   1      1
'管理员1'   2      2
'管理员1'   4      1
'管理员2'   1      3
'管理员4'   1      2
'管理员4'   4      1说明:这个表数量级2000万行左右,最好效率高点,谢谢了

解决方案 »

  1.   

    select name,level,count(*) 次数
    from tablea
    group by name,level
      

  2.   


    要name出现次数最多的前3名的数据
      

  3.   


    select name,level,count(*) as 次数
    from tb
    group by name,level
    having count(*)>=3
      

  4.   


    select name,level,count(*) 次数
    from (
          select name,level,row_number()over(partition by name order by cnt desc) rn 
          from( select name,level,count(*)over(partition by name) cnt from tab)
    )where rn<=3 
    group by name,level
      

  5.   

    SQL> 
    SQL> with taba as (
      2  select 111 id ,'管理员1' name , '登陆' reason, 1 level1 from dual union all
      3  select 112 id ,'管理员1' name ,  '重复登陆' reason, 2 level1 from dual union all
      4  select 113 id ,'管理员1'  name , '重复登陆' reason, 2 level1 from dual union all
      5  select 114 id ,'管理员1' name ,  '退出' reason, 4 level1 from dual union all
      6  select 115 id ,'管理员2'  name , '登陆' reason, 1 level1 from dual union all
      7  select 115 id ,'管理员2' name ,  '修改' reason, 1 level1 from dual union all
      8  select 200 id ,'管理员2'  name , '注销' reason, 1 level1 from dual union all
      9  select 201 id ,'管理员3' name ,  '删除' reason, 2 level1 from dual union all
     10  select 202 id ,'管理员4'  name , '登陆' reason, 1 level1 from dual union all
     11  select 204 id ,'管理员4'  name , '登陆'  reason, 1 level1 from dual union all
     12  select 204 id ,'管理员5'  name , '退出'  reason, 4 level1 from dual
     13  )
     14  select name, level1, cnt
     15    from (select name,
     16                 level1,
     17                 cnt,
     18                 tcnt,
     19                 dense_rank() over(order by tcnt desc) t
     20            from (select name,
     21                         level1,
     22                         count(*) cnt,
     23                         sum(count(*)) over(partition by name order by 1) tcnt
     24                    from taba
     25                   group by name, level1
     26                   order by tcnt desc, name))
     27   where t <= 3
     28  ;NAME           LEVEL1        CNT
    ---------- ---------- ----------
    管理员1             1          1
    管理员1             4          1
    管理员1             2          2
    管理员2             1          3
    管理员4             1          2SQL