您可以将 simlpe SERIAL 列添加到您的表中(它会为您提供事物的顺序),然后使用类似:
SELECT *, row_number() OVER (PARTITION BY month ORDER BY serial_column)
FROM table
这会给你想要的结果。
如果您不需要对行进行排序,您可以尝试:
SELECT *, row_number() OVER (PARTITION BY month)
FROM table
详情在这里:row_number() OVER(...)
UPD 工作原理:
SERIAL 类型的列本质上是一个“自动增量”字段。它会自动从序列中获取一个值。当您向表中插入行时,它们将如下所示:
| MONTH | SERIAL_COLUMN | DESCRIPTION |
-----------------------------------------------------------
| 1 | 1 | One thing |
| 1 | 2 | Another thing |
| 1 | 3 | Last task of the month |
| 2 | 4 | First of second month |
| 2 | 5 | Second and last of second month |
| 3 | 6 | First of third month |
关键 - 每一个下一个添加行的值都比前面的所有行都为SERIAL_COLUMN 大于。
接下来。 row_number() OVER (PARTITION BY month ORDER BY serial_column) 确实:
1) 将所有行划分为具有相等month (PARTITION BY month) 的组
2) 按serial_column (ORDER BY serial_column) 的值对它们进行排序
3) 在每个组中使用第 2 步中的顺序分配一个行号 (`row_number() OVER)
输出是:
| MONTH | SERIAL_COLUMN | DESCRIPTION | ROW_NUMBER |
------------------------------------------------------------------------
| 1 | 1 | One thing | 1 |
| 1 | 2 | Another thing | 2 |
| 1 | 3 | Last task of the month | 3 |
| 2 | 4 | First of second month | 1 |
| 2 | 5 | Second and last of second month | 2 |
| 3 | 6 | First of third month | 1 |
要更改row_number() 的输出,您需要更改SERIAL_COLUMN 中的值。例如,将Second and last of second month 放在First of second month 之前会改变SERIAL_COLUMN 的值,如下所示:
UPDATE Table1
SET serial_column = 5
WHERE description = 'First of second month';
UPDATE Table1
SET serial_column = 4
WHERE description = 'Second and last of second month';
它将改变查询的输出:
| MONTH | SERIAL_COLUMN | DESCRIPTION | ROW_NUMBER |
------------------------------------------------------------------------
| 1 | 1 | One thing | 1 |
| 1 | 2 | Another thing | 2 |
| 1 | 3 | Last task of the month | 3 |
| 2 | 4 | Second and last of second month | 1 |
| 2 | 5 | First of second month | 2 |
| 3 | 6 | First of third month | 1 |
SERIAL_COLUMN 中的确切值无关紧要。 他们只对一个月内的任务进行排序。
我的 SQLFiddle 示例是 here。