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);
最佳答案
这是有效的解决方案。
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
命令,直到不再有重复项为止。这只是一个“它并不完美”的问题,因为它只是一次性操作。
关于sql - 重新编号重复项,使它们独一无二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13137699/