Oracle中rank函数详解
【格式】
格式一:RANK() OVER ( [partition by 分區(qū)字段] order by?排序字段 asc/desc)
格式二:DENSE_RANK() OVER ( [partition by 分區(qū)字段] order by?排序字段 asc/desc)
【說明】
- rank():表示排序結(jié)果不連續(xù);
- dense_rank():表示排序結(jié)果連續(xù);
- partition by:表示分區(qū)統(tǒng)計,該項為可選項;
- order by:表示按指定字段進行排序。
【創(chuàng)建樣例數(shù)據(jù)】
?先創(chuàng)建數(shù)據(jù)表,建表語句如下:
-- Create table
create table T_PRODUT_SALES
(
? product VARCHAR2(20) not null,
? area ? ?VARCHAR2(20) not null,
? sale ? ?NUMBER not null
)
tablespace TEST_SPACE
? pctfree 10
? initrans 1
? maxtrans 255;
-- Add comments to the table?
comment on table T_PRODUT_SALES
? is '產(chǎn)品銷量表-演示用';
-- Add comments to the columns?
comment on column T_PRODUT_SALES.product
? is '產(chǎn)品名稱';
comment on column T_PRODUT_SALES.area
? is '地區(qū)';
comment on column T_PRODUT_SALES.sale
? is '銷量';
再往表中插入數(shù)據(jù),SQL語句如下:
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品1', '地區(qū)1', 50);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品1', '地區(qū)2', 60);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品1', '地區(qū)3', 70);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品2', '地區(qū)1', 50);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品2', '地區(qū)2', 65);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品2', '地區(qū)3', 75);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品3', '地區(qū)1', 40);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品3', '地區(qū)2', 60);
insert into T_PRODUT_SALES (product, area, sale)
values ('產(chǎn)品3', '地區(qū)3', 85);
最后查詢表中數(shù)據(jù),返回結(jié)果如下:
【樣例展示1】
?sql語句如下:
select product,area,sale,rank() over(order by sale desc) as 排名 from T_PRODUT_SALES
返回結(jié)果如下圖:按銷量進行不連續(xù)排名。
【樣例展示2】
??sql語句如下:
select product,area,sale,dense_rank() over(order by sale desc) as 排名 from T_PRODUT_SALES
返回結(jié)果如下圖:按銷量進行連續(xù)排名。
【樣例展示3】
??sql語句如下:
select product,area,sale,rank() over(partition by area order by sale desc) as 排名 from T_PRODUT_SALES
返回結(jié)果如下圖:按地區(qū)分區(qū)進行不連續(xù)排名。
【樣例展示4】
??sql語句如下:
?select product,area,sale,dense_rank() over(partition by area order by sale desc) as 排名 from T_PRODUT_SALES
返回結(jié)果如下圖:按地區(qū)分區(qū)進行連續(xù)排名。
?
總結(jié)
以上是生活随笔為你收集整理的Oracle中rank函数详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天生量化将才?理工科程序员 做量化投资优
- 下一篇: linux 内核PCI驱动总结记录