您的位置:首页 > 数据库 > Oracle

Oracle中 row_number() over()分析函数

2014-01-22 16:51 405 查看
语法格式:row_number() over(partition by 分组列 order by 排序列 desc)

一个很简单的例子

1,先做好准备

create table test1(
id varchar(4) not null,
name varchar(10) null,
age varchar(10) null
);

select * from test1;

insert into test1(id,name,age) values(1,'a',10);
insert into test1(id,name,age) values(1,'a2',11);
insert into test1(id,name,age) values(2,'b',12);
insert into test1(id,name,age) values(2,'b2',13);
insert into test1(id,name,age) values(3,'c',14);
insert into test1(id,name,age) values(3,'c2',15);
insert into test1(id,name,age) values(4,'d',16);
insert into test1(id,name,age) values(5,'d2',17);


2,开始使用之~

select t.id,
t.name,
t.age,
row_number() over(partition by t.id order by t.age asc) rn
from test1 t


结果:

  id name age rn

  1   a    10   1
  1   a2   11  2
  2   b    12   1
  2   b2   13   2
  3   c    14   1
  3   c2   15   2
  4   d    16   1
  5   d2   17   1

3,进一步排序

select * from (select t.id,
t.name,
t.age,
row_number() over(partition by t.id order by t.age asc) rn
from test1 t) where rn < 2


结果:

  id name age rn

  1   a   10   1
  2   b   12   1
  3   c   14   1
  4   d   16   1
  5   d2   17   1

4,总结

  工作半年的经验来看,基本上row_number() over()这个函数主要用在各种数据统计的sql中,感觉比group by好用的都,可以在一个查询中对多列数据进行分组,尤其在多表关联查询中,row_number() over()还是非常便捷的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: