在Postgres中为每个id添加序列号

时间:2016-08-26 19:52:59

标签: postgresql insert create-table

我必须在postgres中创建包含serno,id,name,address的表,serno应该是来自其他表的每个id的运行编号。我有以下查询

CREATE TABLE Ids (SerNo integer, Id varchar(100),Name varchar(250),Address varchar(500));

INSERT INTO Ids (SerNo,Id,Name,Address) 
VALUES (rank() OVER(ORDER BY "Id"),
(SELECT distinct("Id") from   "Table2"),'John','US');

ERROR:  window functions are not allowed in VALUES
LINE 2: VALUES (rank() OVER(ORDER BY "Id"),

请纠正我

1 个答案:

答案 0 :(得分:1)

使用序列:

create table Ids (SerNo serial...

insert into Ids (Id,Name,Address) 
select distinct Id, 'John', 'US'
from Table2;

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL