Oracle--10(ROW_NUMBER() OVER)

1、定義函數

語法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)spa

簡單的說row_number()從1開始,爲每一條分組記錄返回一個數字,這裏的ROW_NUMBER() OVER (ORDER BY xlh DESC) 是先把xlh列降序,再爲降序之後的每條xlh記錄返回一個序號。 
示例: 
xlh           row_num 
1700              1 
1500              2 
1085              3 
710                4code

2、語法orm

row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根據COL1分組,在分組內部根據 COL2排序,而此函數計算的值就表示每組內部排序後的順序編號(組內連續的惟一的)排序

3、例子ci

初始化數據it

create table employee (empid int ,deptid int ,salary decimal(10,2))
insert into employee values(1,10,5500.00)
insert into employee values(2,10,4500.00)
insert into employee values(3,20,1900.00)
insert into employee values(4,20,4800.00)
insert into employee values(5,40,6500.00)
insert into employee values(6,40,14500.00)
insert into employee values(7,40,44500.00)
insert into employee values(8,50,6500.00)
insert into employee values(9,50,7500.00)io

數據顯示爲table

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

需求:根據部門分組,顯示每一個部門的工資等級

預期結果:

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

4、Row_Number() OVER 去重詳解
 SELECT *
          FROM (SELECT K.USRID,
                ROW_NUMBER() OVER(PARTITION BY USRID ORDER BY RECVTIME DESC) ROW_NUM
                  FROM STAGE.TS_A_TRADECOMPFEE K
                 )
         WHERE ROW_NUM = 1;

若是這張表中有兩條除RECVTIME外徹底同樣的記錄,而如今咱們只須要一條,那麼就能夠用這種方法去重,經過ROW_NUMBER() OVER函數經過RECVTIME排序,下邊令ROW_NUM = 1就能夠找到一條記錄了,這樣能夠去冗餘。

 

注意:在使用over等開窗函數時,over裏頭的分組及排序的執行晚於「where,group by,order by」的執行。

以下代碼:


  1. select   

  2. ROW_NUMBER() over(partition by customerID  order by insDT) as rows,  

  3. customerID,totalPrice, DID  

  4. from OP_Order where insDT>'2011-07-22' 

以上代碼是先執行where子句,執行完後,再給每一條記錄進行編號。

相關文章
相關標籤/搜索