我在PostgreSQL中有一个如下表格
表格1date_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
我需要添加一个列record_num
,它从1开始,每个记录自动递增1到表 - 由于权限限制,我无法更改表,因此需要通过{{1操作。
预期输出如下所示。
表2select
编辑:
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
中的日期时间不合规。但table1
需要按照record_num
中的顺序排列。
答案 0 :(得分:1)
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;
答案 1 :(得分:-2)
使用row_number生成序列:
Select row_number() over(order by reg_no) Sno,* from Table1
OR
如果没有唯一列,则创建一个序列,然后将其与select:
一起使用 CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
select NEXT VALUE FOR seq_person AS FirstUse,* from table1