/* Top 10 Analysis Using Rank() Over */
-- 建立測試資料表:
create table rank_over_test
(id varchar2(12),
point number(10)
) pctfree 10 pctused 75;
-- 寫入測試資料
declare
v_id varchar2(12) default null;
v_point number(10) default 0;
begin
for i in 1..20 loop
v_id:='test'||lpad(i,3,0);
v_point:=trunc(dbms_random.value(1,10000));
insert into rank_over_test(id,point)
values(v_id,v_point);
end loop;
commit;
end;
/
-- 測試資料列表:
select * from rank_over_test;
ID
POINT
test001
844
test002
8846
test003
2737
test004
3550
test005
3222
test006
2934
test007
2710
test008
9739
test009
5780
test010
3110
test011
6947
test012
8478
test013
7416
test014
9846
test015
2606
test016
7564
test017
7196
test018
511
test019
7840
test020
4347
-- 傳統Top 10 方法:
select rownum as rank,id,point
from
(
select id,point
from rank_over_test
order by point desc
) where rownum <=10;
RANK
ID
POINT
1
test014
9846
2
test008
9739
3
test002
8846
4
test012
8478
5
test019
7840
6
test016
7564
7
test013
7416
8
test017
7196
9
test011
6947
10
test009
5780
-- Rank() Over Top 10 方法:
select rank,id,point
from
(
select id,point,rank() over(order by point desc) as rank
from rank_over_test
) where rownum <=10;
RANK | ID | POINT |
1 | test014 | 9846 |
2 | test008 | 9739 |
3 | test002 | 8846 |
4 | test012 | 8478 |
5 | test019 | 7840 |
6 | test016 | 7564 |
7 | test013 | 7416 |
8 | test017 | 7196 |
9 | test011 | 6947 |
10 | test009 | 5780 |