如何在Redshift中创建行号?

6
我希望使用SELECT语句创建一个表,并添加一列行号。因此,我想写类似以下的代码:
create table schema.table_w_rownumbers as 
select 
    identity(1, 1) as nrum,
    foo.*
from schema.initial_table as foo;

可能是在Postgres中选择行号的重复问题。 - usr
你需要行号还是自增列?将来是否会向table_w_rownumbers表中插入数据并希望值自动递增? - SQLChao
@usr - 您使用类似的代码时出现了此错误:ERROR: 排名窗口函数需要order by子句。 - d_a_c321
@JChao - 我不会插入数据。我的目标是测试两个Redshift表是否完全相同,如此处所述:http://stackoverflow.com/questions/24436540/how-do-i-tell-if-two-tables-in-redshift-are-exactly-identical - d_a_c321
2个回答

11

这对我起作用了!

create table schema.table_w_rownumbers as 
select 
  row_number() over (partition by 1) as nrum,
  foo.*
from schema.initial_table as foo;

1

尝试此代码。确保将 order by id 更改为其需要按照的顺序。

Create Table schema.table_w_rownumbers
AS
(
select row_number() over (order by id) as nrum, * schema.initial_table
);

2
在这种情况下,我不想按任何方式对其进行排序。我希望行号与它们在select语句中返回的顺序相对应。 - d_a_c321
除非特别指定,否则不保证顺序。因此,由select语句返回的集合可能会有所变化,例如如果添加/删除/更改索引。既然您正在比较数据,那么同时排序有什么问题呢? - SQLChao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接