在SQL 中對分區組內的行進行順序編號
問題:
如何指派使用特定屬性作為分割區的SQL 表中每個鍵組內的連續行號因子?
按鍵組分區:
目標是為指定鍵列或列組合中的每個唯一值順序遞增行號。例如,如果表包含 (CODE, NAME) 的元組,您可能想要將連續編號分配給具有相同 CODE 值的行,如下所示:
原始表:
CODE | NAME |
---|---|
A | Apple |
A | Angel |
A | Arizona |
B | Bravo |
C | Charlie |
C | Cat |
D | Dog |
D | Doppler |
D | Data |
D | Down |
依序分區的行號的期望結果程式碼:
CODE | C_NO | NAME |
---|---|---|
A | 0 | Apple |
A | 1 | Angel |
A | 2 | Arizona |
B | 0 | Bravo |
C | 1 | Charlie |
C | 0 | Cat |
D | 0 | Dog |
D | 1 | Data |
D | 2 | Down |
D | 3 | Doppler |
實作:
多種SQL 方言透過ROW_NUMBER() OVER () 分析函數支援此功能:
SQL伺服器:
SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
Oracle:
SELECT CODE, RANK() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
Pos tgres:
SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
Sybase:
SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
MySQL 8.0 :
SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
MySQL 8.0 :
MariaDB 10.2 :SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
SQLite 3.25 :
SELECT CODE, ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO, NAME FROM MyTable
以上是如何在 SQL 中指派分割區組內的連續行號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!