Resequencing a column with identifier in Postgresql
The following code works and creates a temporary table with a sequence number which is restarted for every new name:
with results as (select row_number() over (partition by name order BY name) as mytid,name from telephn_table)
select * from results order by name
My objective howev开发者_JAVA百科er is to insert the new sequence number permanently into the telephone table. How do I transfer the new sequence number from the results table to the telephone table? I have come across the following for MySql but was not able to convert it to Postgresql.
MySQL: Add sequence column based on another field
Can anyone help?
If memory serves, row_number()
returns the number within its own partition. In other words, row_number() over (partition by name order BY name)
would return 1 for each row except duplicates. You likely want rank() over (order by name)
instead.
After a long discussion:
update telephn_table
set sid = rows.new_sid
from (select pkey,
row_number() over (partition BY name) as new_sid,
name
from telephn_table
) as rows
where rows.pkey = telephn_table.pkey;
THIS WORKS! (See my OP link to a previous MySql link. In Postgresql it works without need for a temporary table)
alter table telephn_table add column tid integer default 0; UPDATE telephn_table set tid=(SELECT count(*)+1 from telephn_table t where t.sid < telephn_table.sid and telephn_table.name=t.name)
精彩评论