1

Now the table structure and data are like below:

Name      record_number        Area
a         1                    CN
a         3                    DE
a         4                    FR
a         6                    DE
b         1                    DE
b         2                    CN

the primary key is (name, record_number)

the record_nubmer was generated by max(record_number) + 1, just assume that there are two records were deleted by record_number = 2/5 and name = 'a', so can anyone tell me how to remove record_nubmer gaps in the table above after deleting and the final results should be like this:

Name      record_number        Area
a         1                    CN
a         2                    DE
a         3                    FR
a         4                    DE
b         1                    DE
b         2                    CN
4

2 回答 2

0

受@AmirPashazadeh 的启发rank(),这是一个单行解决方案:

UPDATE my_table t3
  SET record_number=(SELECT
   t2.rank
   FROM my_table t1
   INNER JOIN (SELECT
    name,
    record_number,
    rank() over (partition by name ORDER BY record_number) rank
    FROM my_table) t2 ON (t1.name=t2.name AND t1.record_number=t2.record_number)
   WHERE t1.name=t3.name AND t1.record_number=t3.record_number);

SQL Fiddle 演示

于 2013-10-28T05:31:21.050 回答
0

您可以使用delete命令更新记录,例如:

update my_table set record_number = record_number - 1
where name = :old.name and record_number > :old.record_number

我不确定您是否可以创建此触发器(而且我现在无法访问 Oracle 部署)。

尝试创建这样的触发器(在删除每一行之后),如果没有,更新应用程序,所以在每次删除之后,上面的查询都会被执行。

另一种解决方案是,执行以下查询:

select name, record_number, rank() over (partition by name order by record_number) new_record_number
  from my_table

现在迭代结果,并执行:

update my_table
   set record_number = :new_record_number
 where name = :name and
       record_number = :record_number

整个事情可以变成一个存储过程,然后在每次删除命令之后调用它。

于 2013-10-28T05:00:24.060 回答