例:
select 1 a,2 b,3 c from dual
union all
select 2 a,6 b,7 c from dual
union all
select 1 a,3 b,4 c from dual
union all
select 2 a,5 b,6 c from dual
union all
select 1 a,4 b,5 c from dual
结果:
1、使用row_number() over (partition by..order by...)可以对这些数据进行分组排序显示。如下
select d.*,row_number() over(partition by a order by a) rownumber from --根据a分组,并且根据a排序
(
select 1 a,2 b,3 c from dual
union all
select 2 a,6 b,7 c from dual
union all
select 1 a,3 b,4 c from dual
union all
select 2 a,5 b,6 c from dual
union all
select 1 a,4 b,5 c from dual
)d
2、所以可以根据这个函数可以满足每一个分组取一种数据。
select * from (select d.*,row_number() over(partition by a order by a) rownumber from
(select 1 a,2 b,3 c from dual
union all select 2 a,6 b,7 c from dual
union all select 1 a,3 b,4 c from dual
union all select 2 a,5 b,6 c from dual
union all select 1 a,4 b,5 c from dual)d
)where rownumber=1 --取得每一组的第一个
3、使用rownum的情况
select d.*,rownum rownumber from --使用rownum
(select 1 a,2 b,3 c from dual
union all select 2 a,6 b,7 c from dual
union all select 1 a,3 b,4 c from dual
union all select 2 a,5 b,6 c from dual
union all select 1 a,4 b,5 c from dual)d
两者区别:rownum是将查询的结果直接加入伪列,而row_number() over (partition by..order by...)是将查询的结果先分组排序再加入伪列。