有一张表,非常大,估计有上亿数据。是用来记录客户操作日志的。现在针对这张表想取出每位客户最近所做的五个不同的操作,怎样达到这个效果呢?表结构如下:
USER_ID,OP_CODE,OP_TIME
分别是客户ID,操作代码,操作时间。还有很多其他乱七八糟的字段,这里不用关心。
在USER_ID,OP_TIME里建有索引。因为需要用OP_CODE关联其他表,所以这里取出来的只能是这个字段,其他字段不要。
例如某位客户的操作信息如下,怎么写出比较高效的查询语句呢?
USER_ID    OP_CODE    OP_TIME
001        A          2010-12-02 12:02:02
001        B          2010-11-02 12:02:02
001        A          2010-10-02 12:02:02
001        B          2010-09-02 12:02:02
001        F          2010-08-02 12:02:02
001        C          2010-07-02 12:02:02
001        A          2010-06-02 12:02:02
001        D          2010-05-02 12:02:02
001        E          2010-04-02 12:02:02
001        A          2010-03-02 12:02:02
001        F          2010-02-02 12:02:02
001        F          2010-01-02 12:02:02
001        F          2010-01-02 12:02:02
需要取出来的是A B F C D
在此现行谢过~~

解决方案 »

  1.   

    select
        user_id, 
        op_code
      from (select
                user_id,
                op_code,
                row_number() over(partition by user_id,op_code order by op_time desc) index_code
              from 表 
            )
     where index_code <= 5
      

  2.   

    select distinct(OP_CODE) from 表 where 条件
      

  3.   

    select op_code
    from
    (
    select user_id,op_code,max(op_time) op_time,rownum row_num
    from abc
    group by user_id,op_code
    order by op_time desc
    )
    where user_id='001' and row_num<=5
      

  4.   

    select distinct   last_value(user_id) over(partition by user_id,op_code order by op_time desc 
                   range between unbounded preceding and unbounded following) user_id_0,
    last_value(op_code) over(partition by user_id,op_code order by op_time desc 
                   range between unbounded preceding and unbounded following) op_code_0  from 表  如果user_id 不要,那你怎么知道是哪个用户?还是用户已知了?那就更简单
    select distinct last_value(op_code) over(partition by user_id,op_code order by op_time desc 
                   range between unbounded preceding and unbounded following) op_code_0
      from 表  where user_id = 已知
      

  5.   

    这个可以一试:select *
      from (select user_id, op_code, rownum rn
              from (select user_id, op_code from bigt group by user_id, op_code))
     where rn <= 5