1、row_number() over()排序功能:
(1) row_number() over()分组排序功能:
在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where group by order by 的执行。
partition by 用于给结果集分组,如果没有指定那么它把整个结果集作为一个分组,它和聚合函数不同的地方在于它能够返回一个分组中的多条记录,而聚合函数一般只有一个反映统计值的记录。
例如:emp,根据部门分组排序。
sql> select empno,deptno,sal,row_number() over (partition by deptno order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 77821024502 79341013003 77882030001 79022030002 75662029753 78762011004 7369208005 76983028501 74993016002 78443015003 76543012504 75213012505 7900309506 14rowsselected.
(2)对查询结果进行排序:(无分组)
sql> select empno,row_number() over (order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 79022030002 77882030003 75662029754 76983028505 77821024506 74993016007 78443015008 79341013009 752130125010 765430125011 787620110012 79003095013 73692080014 14rowsselected.
row_number() over()和rownum差不多,功能更强一点(可以在各个分组内从1开时排序).
2、rank() over()是跳跃排序,有两个第二名时接下来就是第四名(同样是在各个分组内).
sql> select empno,rank() over (partition by deptno order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 77821024502 79341013003 77882030001 79022030001 75662029753--跳跃了 78762011004 7369208005 76983028501 74993016002 78443015003 76543012504 75213012504 7900309506 14rowsselected.
sql> select empno,rank() over (order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 79022030002 77882030002 75662029754--跳跃了 76983028505 77821024506 74993016007 78443015008 79341013009 752130125010 765430125010 787620110012 79003095013 73692080014 14rowsselected.
3、dense_rank() over()是连续排序,有两个第二名时仍然跟着第三名。相比之下row_number是没有重复值的 .
sql> select empno,dense_rank() over (order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 79022030002 77882030002 75662029753 76983028504 77821024505 74993016006 78443015007 79341013008 75213012509 76543012509 787620110010 79003095011 73692080012 14rowsselected.
sql> select empno,dense_rank() over (partition by deptno order by sal desc) rank from emp;
EMPNODEPTNOSALRANK ---------------------------------------- 78391050001 77821024502 79341013003 77882030001 79022030001 75662029752--不跳跃 78762011003 7369208004 76983028501 74993016002 78443015003 76543012504 75213012504 7900309505 14rowsselected.
使用ROW_NUMBER删除重复数据
---假设表TAB中有a,b,c三列,可以使用下列语句删除a,c都相同的重复行。
DELETE FROM (select year,QUARTER,RESULTS,row_number() over(partition by YEAR,RESULTS order by YEAR,RESULTS) AS ROW_NO FROM SALE )
WHERE ROW_NO>1