如何删除并保留最新条目

时间:2016-06-23 09:30:08

标签: sql sql-server ms-access

我正在解决一个问题,我的表A有列:

1) Contact number
2) name
3) address
4) date updated

现在因为没有多次定义的主键记录插入了相同的手机号码。我只想保留最新日期更新记录。

例如:

8018725398       Nikhil     Bangalore     22/4/2016
8018725398       Nikhil     Chennai       22/05/2016
8018725398       Nikhil      lucknow      22/06/2016

现在我想保留最后一条记录,而不是前两条或前n条记录。有数千个记录,其中100个正在重复。怎么做?

6 个答案:

答案 0 :(得分:4)

取决于您的RDBMS,对于ANSI-SQL,您可以使用ROW_NUMBER()

WITH dups AS (
SELECT ROW_NUMBER() OVER (PARTITION BY contact_Number ORDER BY date_updated DESC) AS duplicate
FROM TableA)

DELETE FROM dups WHERE duplicate>1;

或者EXISTS()适用于所有RDBMS:

DELETE FROM TableA t
WHERE EXISTS(SELECT 1 FROM TableA s
             WHERE t.contact_number = s.contact_number
               AND t.date_updated < s.date_updated)

答案 1 :(得分:1)

插入表格

Select 
T.Contactnumber,
T.name,
T.address,
TT.Maxdate  
from tableA  T
INNER JOIN (
Select Contactnumber,MAX(dateupdated)Maxdate FROM tableA 
GROUP BY Contact number,name,address)TT
ON T.Contactnumber = TT.Contactnumber

答案 2 :(得分:1)

SELECT *
FROM table_a a
WHERE EXISTS (
    SELECT null
    FROM table_a sub
    WHERE a.contact_number = sub.contact_number
    AND a.date_updated < sub.date_updated );

使用上述内容检查要删除的记录集是否符合预期。然后将其更改为DELETE语句,而不是SELECT

答案 3 :(得分:1)

任务很简单:删除记录,其中存在具有相同编号的后续记录。

delete from mytable
where exists
(
  select *
  from mytable later
  where later.contact_number = mytable.contact_number
  and later.date_updated > mytable.date_updated
);

答案 4 :(得分:1)

在SQL服务器

delete from A  where not exists 
(
    select 1 from 
            ( select [Contact number],max([date updated]) as [date updated] 
             from A 
             group by [Contact number]
            ) as S
where A.[Contact number]=S.[Contact number] 
        and A.[date updated]=S.[date updated]
)

答案 5 :(得分:0)

此选项为您提供上次更新的记录:

select ContactNumber, MAX(DateUpdated) as LastUpdate
    from TableA
    group by ContactNumber

它可以用作子选择来删除行,它们具有相同的ContactNumber但具有不同的DateTime-Value:

delete from TableA
from
    (select ContactNumber, MAX(DateUpdated) as LastUpdate
        from TableA
        group by ContactNumber) A
where TableA.ContactNumber = A.ContactNumber and DateUpdated != LastUpdate