ROW_NUMBER() OVER()函数用法;(分组,排序),partition by

时间:2022-07-05 03:23:40

转载:https://www.cnblogs.com/alsf/p/6344197.html

1、row_number() over()排序功能:

(1) row_number() over()分组排序功能:

在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where group by  order by 的执行。

partition by 用于给结果集分组,如果没有指定那么它把整个结果集作为一个分组,它和聚合函数不同的地方在于它能够返回一个分组中的多条记录,而聚合函数一般只有一个反映统计值的记录。

例如:employee,根据部门分组排序。

ROW_NUMBER() OVER()函数用法;(分组,排序),partition by
SELECT empno,WORKDEPT,SALARY, Row_Number() OVER (partition by workdept ORDER BY salary desc) rank FROM employee
--------------------------------------
000010 A00 152750 1
000110 A00 66500 2
000120 A00 49250 3
200010 A00 46500 4
200120 A00 39250 5
000020 B01 94250 1
000030 C01 98250 1
000130 C01 73800 2
ROW_NUMBER() OVER()函数用法;(分组,排序),partition by

(2)对查询结果进行排序:(无分组)

ROW_NUMBER() OVER()函数用法;(分组,排序),partition by
SELECT empno,WORKDEPT,SALARY, Row_Number() OVER (ORDER BY salary desc) rank FROM employee
--------------------------------------
000010 A00 152750 1
000030 C01 98250 2
000070 D21 96170 3
000020 B01 94250 4
000090 E11 89750 5
000100 E21 86150 6
000050 E01 80175 7
000130 C01 73800 8
000060 D11 72250 9
ROW_NUMBER() OVER()函数用法;(分组,排序),partition by

row_number() over()和rownum差不多,功能更强一点(可以在各个分组内从1开时排序).

2、rank() over()是跳跃排序,有两个第二名时接下来就是第四名(同样是在各个分组内).

ROW_NUMBER() OVER()函数用法;(分组,排序),partition by
select workdept,salary,rank() over(partition by workdept order by salary) as dense_rank_order from emp order by workdept;
------------------
A00 39250 1
A00 46500 2
A00 49250 3
A00 66500 4
A00 152750 5
B01 94250 1
C01 68420 1
C01 68420 1
C01 73800 3
ROW_NUMBER() OVER()函数用法;(分组,排序),partition by

3、dense_rank() over()是连续排序,有两个第二名时仍然跟着第三名。相比之下row_number是没有重复值的 .

ROW_NUMBER() OVER()函数用法;(分组,排序),partition by
select workdept,salary,dense_rank() over(partition by workdept order by salary) as dense_rank_order from emp order by workdept;
------------------
A00 39250 1
A00 46500 2
A00 49250 3
A00 66500 4
A00 152750 5
B01 94250 1
C01 68420 1
C01 68420 1
C01 73800 2
C01 98250 3
ROW_NUMBER() OVER()函数用法;(分组,排序),partition by

使用ROW_NUMBER删除重复数据 
---假设表TAB中有a,b,c三列,可以使用下列语句删除a,b,c都相同的重复行。

DELETE FROM (select year,QUARTER,RESULTS,row_number() over(partition by YEAR,QUARTER,RESULTS order by YEAR,QUARTER,RESULTS) AS ROW_NO FROM SALE )
WHERE ROW_NO>1