你可以向你的表格添加一个简单的
SERIAL
列(它将为你的事物提供顺序),然后使用类似以下的内容:
您可以向表格添加一个简单的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(...)
更新:它的工作原理:
具有类型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
中的值。例如,要将第二个月份的第二和最后一个
放在第二个月份的第一个之前
,需要像这样更改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 示例在此处。
row_number()
。我已经编辑了查询。 - Ihor Romanchenko