[英]SQL - add column with auto increment via select
I have a table like below in PostgreSQL 我在PostgreSQL中有一个如下表
table1 表格1 date_time | make | model | miles | reg_no | age_months ---------------------------------------------------------------------- 2016-09-28 20:05:03.001 | toyota | prius | 10200 | 1111 | 22 2016-09-28 20:05:03.001 | suzuki | sx4 | 10300 | 1122 | 12 2016-09-28 20:03:03.001 | suzuki | sx4 | 11200 | 1133 | 34 2016-09-28 20:02:03.001 | toyota | prius | 15200 | 1144 | 28 2017-05-28 20:11:03.001 | toyota | prius | 15500 | 1144 | 36
I need to add a column record_num
which starts from 1 and auto increment by 1 for every record to the table - I cannot alter the table due to permission restrictions, so it need to be done via select
operation. 我需要在表中添加一列record_num
,该列从1开始,每条记录的自动递增1-由于权限限制,我无法更改该表,因此需要通过select
操作来完成。
The expected output is like as below. 预期的输出如下。
table2 表2 date_time | make | model | miles | reg_no | age_months | record_num ----------------------------------------------------------------------------------- 2016-09-28 20:05:03.001 | toyota | prius | 10200 | 1111 | 22 | 1 2016-09-28 20:05:03.001 | suzuki | sx4 | 10300 | 1122 | 12 | 2 2016-09-28 20:03:03.001 | suzuki | sx4 | 11200 | 1133 | 34 | 3 2016-09-28 20:02:03.001 | toyota | prius | 15200 | 1144 | 28 | 4 2017-05-28 20:11:03.001 | toyota | prius | 15500 | 1144 | 36 | 5
Edit:
编辑:
The date-time is not in order in table1
. 日期时间是不是为了在table1
。 But the record_num
needs to be in the order as in the table1
. 但是record_num
需要按照table1
中的顺序排列。
Use a window function : 使用窗口功能 :
select date_time,
make,
model,
miles,
reg_no,
age_months,
row_number() over (order by date_time) as record_num
from the_table
order by date_time;
use row_number to generate sequence: 使用row_number生成序列:
Select row_number() over(order by reg_no) Sno,* from Table1
OR 要么
if there is no unique column then create a sequence and then use it with select : 如果没有唯一列,则创建一个序列,然后将其与select一起使用:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
select NEXT VALUE FOR seq_person AS FirstUse,* from table1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.