轉載☞:https://blog.csdn.net/qq_25221835/article/details/82762416
ROW_NUMBER
語法
語法格式:row_number() over(partition by 分組列 order by 排序列 desc)
解釋
row_number() over()分組排序功能:
在使用 row_number() over()函數時候,over()里頭的分組以及排序的執行晚於 where 、group by、 order by 的執行。
示例1
表數據:
create table TEST_ROW_NUMBER_OVER( id varchar(10) not null, name varchar(10) null, age varchar(10) null, salary int null ); select * from TEST_ROW_NUMBER_OVER t; insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a',10,8000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a2',11,6500); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b',12,13000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b2',13,4500); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c',14,3000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c2',15,20000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(4,'d',16,30000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(5,'d2',17,1800);
依次排序:對查詢結果進行排序(無分組)
select id,name,age,salary,row_number()over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t
結果
根據id分組排序
select id,name,age,salary,row_number()over(partition by id order by salary desc) rank from TEST_ROW_NUMBER_OVER t
結果
找出每一組中序號為一的數據
select * from(select id,name,age,salary,row_number()over(partition by id order by salary desc) rank from TEST_ROW_NUMBER_OVER t) where rank <2
結果
排序找出年齡在13歲到16歲數據,按salary排序
select id,name,age,salary,row_number()over(order by salary desc) rank from TEST_ROW_NUMBER_OVER t where age between '13' and '16'
結果:結果中 rank 的序號,其實就表明了 over(order by salary desc) 是在where age between and 后執行的
示例二
使用row_number()函數進行編號
select email,customerID, ROW_NUMBER() over(order by psd) as rows from QT_Customer
在訂單中按價格的升序進行排序,並給每條記錄進行排序代碼如下:
select DID,customerID,totalPrice,ROW_NUMBER() over(order by totalPrice) as rows from OP_Order
統計出每一個各戶的所有訂單並按每一個客戶下的訂單的金額 升序排序,同時給每一個客戶的訂單進行編號。這樣就知道每個客戶下幾單了
select ROW_NUMBER() over(partition by customerID order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order
統計每一個客戶最近下的訂單是第幾次下的訂單
with tabs as ( select ROW_NUMBER() over(partition by customerID order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order ) select MAX(rows) as '下單次數',customerID from tabs group by customerID
篩選出客戶第一次下的訂單
思路。利用rows=1來查詢客戶第一次下的訂單記錄
with tabs as ( select ROW_NUMBER() over(partition by customerID order by insDT) as rows,* from OP_Order ) select * from tabs where rows = 1 select * from OP_Order
注意:在使用over等開窗函數時,over里頭的分組及排序的執行晚於“where,group by,order by”的執行。
select ROW_NUMBER() over(partition by customerID order by insDT) as rows, customerID,totalPrice, DID from OP_Order where insDT>'2011-07-22'