GROUP BY与PARTITION BY的使用

上一篇 / 下一篇  2011-02-18 15:52:47 / 个人分类:数据库

最近有这样的数据需求,要把每个用户的最近100条记录查出来,一上来就用常用的分组函数查,发现语句不好写,如果分区函数查倒比较方便:

分区函数:PARTITION BY
select * from
(
  select a.*,row_number() 
  over (partition by ID order by TIME desc) as rn 
  from user a
) b
where rn<101

后来研究一下如果用分组函数无法满足要求,只能用到循环语句去,这就要求用较高的应用:
create or replace procedure pro_test_cursor_hwt
as
  Id number(20);
  content  varchar2(500);

Cursor cur1 is select t.id from user t where rownum<=30;
Cursor cur2(celId tuser_info.celebrity_id%type) is select Id, content from (select Id, content from tuser_info where Id=celId  order by time desc) where rownum<=100;

begin
       open cur1;
       loop
         fetch cur1 into Id;
         exit when cur1%notfound;

         open cur2(Id);
         loop
             fetch cur2 into Id, content;
             exit when cur2%notfound;
             dbms_output.put_line(Id || '--' || content || '--' || Time);
         end loop;
         close cur2;

       end loop;
       close cur1;
end;

   如果不用分区函数,竟然要费那么大劲才能实现。目前就想这两种方法,如有高手路过,望指点一下。





TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-11  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 1807
  • 日志数: 4
  • 建立时间: 2010-10-28
  • 更新时间: 2011-02-22

RSS订阅

Open Toolbar