Oracle如何删除一张表内的重复数据,但保留最新的一条?

一张表根据customer_guid判断是否重复,删除其中的的重复数据,但保留时间最新的一条。
例如:
customer_guid createddate
12345 2015/2/1 08:00:00
12345 2015/2/9 17:00:00

则删除2月1日的这条数据,保留2月9日的这条。

现在只写出了判断重复的语句,不知道时间怎么判断了,初学Oracle,求助各位大神帮忙解答
DELETE from Table WHERE (customer_guid) IN ( SELECT customer_guid FROM Table GROUP BY customer_guid HAVING COUNT(customer_guid) > 1)

楼主你的这个SQL会将表中所有重复的数据都给删掉的,包括你要保留的最新的时间戳的数据。其实你的这个SQL知识查询出来的那些数据是重复的,至于要删除那条数据,你的这个SQL定位不到。
查询出你想要删除的重复数据用下面的SQL:
select * from table a where a.createdate < (select max(b.createdate) from table b where a.customer_guid=b.customer_guid);
删除的话就用这个了:
delete from table a where a.createdate < (select max(b.createdate) from table b where a.customer_guid=b.customer_guid);
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-02-09

参考这个

DELETE from Table t1
WHERE createddate != ( SELECT max(createddate)
FROM Table t2 
where t2.customer_guid=t1.customer_guid)
and exists ( select count(customer_guid)
from Table t3
where t3.customer_guid=t1.customer_guid
having count(customer_guid)>1 );

本回答被提问者和网友采纳
相似回答