原文地址:https://blog.csdn.net/qq_30908543/article/details/74108348
注:mysql貌似不適用,本人測試未成功,mysql實現方式可參考:https://www.cnblogs.com/phpk/p/10935655.html
實例如下:
1.使用row_number()函數進行編號,如
select email,customerID, ROW_NUMBER() over(order by psd) as rows from QT_Customer
原理:先按psd進行排序,排序完后,給每條數據進行編號。
2.在訂單中按價格的升序進行排序,並給每條記錄進行排序代碼如下:
select DID,customerID,totalPrice,ROW_NUMBER() over(order by totalPrice) as rows from OP_Order
3.統計出每一個各戶的所有訂單並按每一個客戶下的訂單的金額 升序排序,同時給每一個客戶的訂單進行編號。這樣就知道每個客戶下幾單了。
如圖:
代碼如下:
select ROW_NUMBER() over(partition by customerID order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order
4.統計每一個客戶最近下的訂單是第幾次下的訂單。
代碼如下:
- 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
5.統計每一個客戶所有的訂單中購買的金額最小,而且並統計改訂單中,客戶是第幾次購買的。
如圖:
上圖:rows表示客戶是第幾次購買。
思路:利用臨時表來執行這一操作。
1.先按客戶進行分組,然后按客戶的下單的時間進行排序,並進行編號。
2.然后利用子查詢查找出每一個客戶購買時的最小價格。
3.根據查找出每一個客戶的最小價格來查找相應的記錄。
代碼如下:
- with tabs as
- (
- select ROW_NUMBER() over(partition by customerID order by insDT) as rows,customerID,totalPrice, DID from OP_Order
- )
- select * from tabs
- where totalPrice in
- (
- select MIN(totalPrice)from tabs group by customerID
- )
6.篩選出客戶第一次下的訂單。
思路。利用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
7.rows_number()可用於分頁
思路:先把所有的產品篩選出來,然后對這些產品進行編號。然后在where子句中進行過濾。
8.注意:在使用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'
以上代碼是先執行where子句,執行完后,再給每一條記錄進行編號。