DB2中ROW_NUMBER() OVER函数的基本用法

语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)

简单的说row_number()从1开始,为每一条分组记录返回一个数字,这里的ROW_NUMBER() OVER (ORDER BY COL1 DESC) 是先把COL1列降序,再为降序以后的每条COL1记录返回一个序号。
示例:
Column1           row_num
1700                      1
1500                      2
1085                      3
710                        4

row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)

empid       deptid      salary                                  rank
----------- ----------- --------------------------------------- --------------------
1           10          5500.00                                  1
2           10          4500.00                                  2
4           20          4800.00                                  1
3           20          1900.00                                  2
7           40          44500.00                                1
6           40          14500.00                                2
5           40          6500.00                                  3
9           50          7500.00                                  1
8           50          6500.00                                  2

SQL脚本:

SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee

你可能感兴趣的:(Data,Structure,Algorithm,Oracle,DB2,Mysql)