向postgresql中的列添加递增值
Add incrementing value to the column in postgresql
我有一个 table,其中包含 69000 records
。现在,如何添加一个应该包含 value 1 for 1st row, 2 for 2nd row ....etc
.
的新列(比如索引)
我想要下面的结果
id name index
--------------------------
9796896 sandy 1
796869 raj 2
试试这个:
ALTER TABLE Tablename
ADD COLUMN index int
GENERATED BY DEFAULT AS IDENTITY;
你可以使用oracle的标识列:
alter table your_Table add index_ number GENERATED by default as IDENTITY;
另外,您可以添加列然后为其赋值:
alter table your_Table add index_ number;
update your_Table tt
set tt.index_ = (select rn from (
select row_number() over (order by id desc) rn
from your_Table t
) t where t.id = tt.id)
干杯!!
添加列并用类似的内容更新它:
with cte as
(
select *
, rank() over (order by id desc) as ranker
from test
)
update test
set index = ranker
from cte
where cte.id = test.id;
我有一个 table,其中包含 69000 records
。现在,如何添加一个应该包含 value 1 for 1st row, 2 for 2nd row ....etc
.
我想要下面的结果
id name index
--------------------------
9796896 sandy 1
796869 raj 2
试试这个:
ALTER TABLE Tablename
ADD COLUMN index int
GENERATED BY DEFAULT AS IDENTITY;
你可以使用oracle的标识列:
alter table your_Table add index_ number GENERATED by default as IDENTITY;
另外,您可以添加列然后为其赋值:
alter table your_Table add index_ number;
update your_Table tt
set tt.index_ = (select rn from (
select row_number() over (order by id desc) rn
from your_Table t
) t where t.id = tt.id)
干杯!!
添加列并用类似的内容更新它:
with cte as
(
select *
, rank() over (order by id desc) as ranker
from test
)
update test
set index = ranker
from cte
where cte.id = test.id;