我想删除sql中的重复行。我的表看起来像这样:
CREATE TABLE test_table
(
id Serial,
Date Date,
Time Time,
Open double precision,
High double precision,
Low double precision
);
DELETE FROM test_table
WHERE ctid IN (SELECT min(ctid)
FROM test_table
GROUP BY id
HAVING count(*) > 1);
使用以下delete
语句,我在秘密列ctid
中搜索重复的条目并删除它们。但是这不能正常工作。查询正确执行,但不删除任何内容。
感谢您的回答!
更新
这是一些示例数据(没有生成的id
):
2013.11.07,12:43,1.35162,1.35162,1.35143,1.35144
2013.11.07,12:43,1.35162,1.35162,1.35143,1.35144
2013.11.07,12:44,1.35144,1.35144,1.35141,1.35142
2013.11.07,12:45,1.35143,1.35152,1.35143,1.35151
2013.11.07,12:46,1.35151,1.35152,1.35149,1.35152
答案 0 :(得分:2)
摆脱使用ctid
,xid
等习惯 - 他们不会因为某个原因而被宣传。
一次处理重复行的一种方法,具体取决于你的postgres版本最近的版本:
with unique_rows
as
(
select distinct on (id) *
from test_table
),
delete_rows
as
(
delete
from test_table
)
insert into test_table
select *
from unique_rows
;
或者通过三个步骤分解所有内容并使用临时表:
create temp table unique_rows
as
select distinct on (id) *
from test_table
;
create temp table delete_rows
as
delete
from test_table
;
insert into test_table
select *
from unique_rows
;
答案 1 :(得分:0)
不确定你是否可以在postgresql中使用row_number和partiontions但如果是这样你可以这样做来查找重复项,你可以从partion中添加或减去列来定义集合中的重复项
WITH cte AS
(
SELECT id,ROW_NUMBER() OVER(PARTITION BY Date, Time ORDER BY date, time) AS rown
FROM test_table
)
delete From test_table
where id in (select id from cte where rown > 1);