【问题标题】:SQL - add column with auto increment via selectSQL - 通过选择添加具有自动增量的列
【发布时间】:2017-04-08 16:55:39
【问题描述】:

我在 PostgreSQL 中有一个如下表

表格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

我需要添加一个从 1 开始的列 record_num,并为表中的每条记录自动递增 1 - 由于权限限制,我无法更改表,因此需要通过 select 操作来完成。

预期的输出如下所示。

表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
编辑:

table1 中的日期时间不按顺序排列。但是record_num 需要按照table1 中的顺序排列。

【问题讨论】:

  • 没有“表格的顺序”这样的东西。关系数据库中的行是 NOT 排序的。 only(真的:唯一)获取特定订单的方法是使用order by
  • 检查我的答案。我认为它适合你的条件

标签: sql postgresql


【解决方案1】:

使用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;

【讨论】:

  • record_num的顺序需要按照原表中数据的顺序-table1-我刚刚编辑了问题
  • 很好,但是如果此列不是唯一的,则 row_number() over(order by some_column) 将不是唯一的 - 相同的日期会给你相同的 row_numbers...我会建议 'row_number () over()' 和按日期排序的子查询。
  • @Jendrusk: row_number() 总是返回唯一的数字。您将其与 rank()dense_rank() 混淆了。见这里:rextester.com/LSZ41415
  • @user3206440:关系数据库中没有“数据的顺序”之类的东西。表中的行以任何方式 NOT 排序。获得保证的行(或数字)顺序的唯一方法是使用order by 语句。没有其他办法。
  • @a_horse_with_no_name - 对不起 - 你是对的,我错了
【解决方案2】:

使用 row_number 生成序列:

Select row_number() over(order by reg_no) Sno,* from Table1

如果没有唯一列,则创建一个序列,然后将其与 select 一起使用:

     CREATE SEQUENCE seq_person
      MINVALUE 1
      START WITH 1
     INCREMENT BY 1

     select NEXT VALUE FOR seq_person AS FirstUse,* from table1

【讨论】:

  • select NEXT VALUE FOR seq_person 对 Postgres 无效
  • 是的,我知道。你只是谷歌如何在 postgresql 中创建序列
猜你喜欢
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多