在 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
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 表中每个键组内的连续行号。
以上是如何在 SQL 中分配分区组内的连续行号?的详细内容。更多信息请关注PHP中文网其他相关文章!