RANK ( ) OVER ( [query_partition_clause] order_by_clause ) DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
可實現按指定的字段進行分組,然后按照另一個字段在分組內進行排序,其中PARTITION BY 為分組字段,ORDER BY 指定排序字段。over不能單獨使用,要和分析函數:rank(),dense_rank(),row_number()等一起使用。其參數:over(partition by columnname1 order by columnname2)。含義:按columname1指定的字段進行分組,然后在分組的基礎之上按照columnname2字段在分組內進行排序。
例如:EMP表中,有三個個部門的記錄:DEPTNO分別為10、20和30。以下SQL就是指在部門10、20和30三個部門中按照薪水進行排序。
select DEPTNO,SAL,rank() OVER(partition by DEPTNO order by SAL DESC) from EMP
同時需要注意rank()、dense_rank()和Row_number()的區別:
例如如下dense_rank和上面rank()語句結果的區別:
select DEPTNO,SAL,DENSE_RANK() OVER(partition by DEPTNO order by SAL) from EMP
對於row_number()結果如下:
select DEPTNO,SAL,row_Number() OVER(partition by DEPTNO order by SAL DESC) from EMP
同時over語句也可以和SUM()語句一起使用,不同的OVER()語句代表不同的求和方式。還以EMP表為例:
select DEPTNO,SAL,SUM(SAL) OVER() 總和,SUM(SAL) OVER(ORDER by SAL) 連續求和 from EMP
select DEPTNO,SAL,SUM(SAL) OVER(partition by deptno) 部門總和,SUM(SAL) OVER(partition by deptno ORDER by SAL) 部門連續求和 from EMP
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。