重新编号重复以使其唯一

时间:2012-10-30 11:08:42

标签: sql postgresql postgresql-8.2

       Table "public.t"
 Column |  Type   | Modifiers
--------+---------+-----------
 code   | text    |
 grid   | integer |

codigo列虽然是文本类型,但却有一个数字序列 重复。网格列是一个独特的序列。

select * from t order by grid;
 code | grid
------+------
 1    |    1
 1    |    2
 1    |    3
 2    |    4
 2    |    5
 2    |    6
 3    |    7

目标是消除code列中的重复项,使其独一无二。结果应类似于:

 code | grid
------+------
 1    |    1
 6    |    2
 4    |    3
 2    |    4
 7    |    5
 5    |    6
 3    |    7

版本为8.2(无窗口功能)。

create table t (code text, grid integer);
insert into t values
 ('1',1),
 ('1',2),
 ('1',3),
 ('2',4),
 ('2',6),
 ('3',7),
 ('2',5);

2 个答案:

答案 0 :(得分:0)

这是有效的解决方案。

drop sequence if exists s;
create temporary sequence s;
select setval('s', (select max(cast(code as integer)) m from t));

update t
set code = i
from (
    select code, grid, nextval('s') i
    from (
        select code, max(grid) grid
        from t
        group by code
        having count(*) > 1
        order by grid
    ) q
) s
where
    t.code = s.code
    and
    t.grid = s.grid

问题在于必须重复update命令,直到不再有重复项为止。它只是一个“它不是完美的”问题,因为它只是一次性操作。

答案 1 :(得分:0)

导出(并删除)除code列以外的所有内容(也许您可以导出子查询,并删除重复的行)。使code主要具有此类自动增量行为并重新导入所有内容。应自动生成code列。