是否有任何内置方式(我的意思是,不需要触发器和/或函数)每个多列都有递增索引?
所以表演后:
INSERT INTO "table" ("month","desc") VALUES (1,'One thing'),(1,'Another thing'),'Last task of the month'),(2,(3,'First of third month')
我的表最终会像这样(注意“任务”列):
month task desc 1 1 One thing 1 2 Another thing 1 3 Last task of the month 2 1 First of second month 2 2 Second and last of second month 3 1 First of third month
您可以将simlpe SERIAL列添加到您的表中(它将为您提供事物的顺序),然后使用以下内容:
原文链接:/postgresql/191958.htmlSELECT *,row_number() OVER (PARTITION BY month ORDER BY serial_column) FROM table
这将为您提供所需的结果.
如果您不需要订购行,可以尝试:
SELECT *,row_number() OVER (PARTITION BY month) FROM table
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)将所有行分成具有相同月份的组(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中的确切值无关紧要.他们只在一个月内就任务设定了订单.