简体   繁体   中英

SQL - add column with auto increment via select

I have a table like below in PostgreSQL

table1
 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.

The expected output is like as below.

table2
 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 . But the record_num needs to be in the order as in the 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:

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 :

     CREATE SEQUENCE seq_person
      MINVALUE 1
      START WITH 1
     INCREMENT BY 1

     select NEXT VALUE FOR seq_person AS FirstUse,* from table1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM