SQL使用ROW_NUMBER() OVER函數生成序列號
語法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
簡單的說
ROW_NUMBER()
從1開始,為每一條分組記錄返回一個數字,這裡的ROW_NUMBER() OVER (ORDER BY CYLH DESC)
是先把xlh列降序,再為降序以後的每條CYLH記錄返回一個序號。
示例:
分析:ROW_NUMBER() OVER (PARTITION BY COL1 ORDER BY COL2)
表示根據COL1分組,在分組內部根據 COL2
排序,而此函數計算的值就表示每組內部排序後的順序編號(組內連續的唯一的)
也可這樣使用:ROW_NUMBER() OVER (ORDER BY COL2)
例子:
建立測試表,並插入測試數據
CREATE TABLE TEST_ROW_NUMBER_01( CMZH varchar(10) not null, CYLH varchar(10) null, MJE money null, );
INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES (2106000011,20281997,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000010,20281996,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000008,20281995,0.00) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000006,20281994,9.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000004,20281993,5.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000001,20281992,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000002,20281992,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000007,20217280,0.00) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000009,20172458,5.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000005,20121813,0.00)
執行腳本自動生成行號並按CYLH進行排序(滑動查看代碼)
SELECT ROW_NUMBER()OVER(ORDER BY CYLH DESC) AS ROWNUM,* FROM TEST_ROW_NUMBER_01
結果如下:
註意:在使用over
等開窗函數時,over
裡頭的分組及排序的執行晚於“where
,group by
,order by
”的執行。
到此這篇關於SQL使用ROW_NUMBER() OVER函數生成序列號的文章就介紹到這瞭,更多相關SQL用ROW_NUMBER() OVER生成序列號內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- sql ROW_NUMBER()與OVER()方法案例詳解
- MYSQL row_number()與over()函數用法詳解
- SQL數據庫的所有命令(函數、運算符)匯總大全
- MySQL中符號@的作用
- SQL查詢至少連續七天下單的用戶