您可以将 simlpeSERIAL
列添加到您的表中(它会给您订单),然后使用类似:
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
)的组
serial_column
2) 按( ORDER BY serial_column
)的值对它们进行排序
`row_number() OVER
3) 在每个组中使用步骤 2 ( )中的排序分配一个行号
输出是:
| 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
a 之前会改变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 示例在这里。