删除重复记录并在sql中的另一个表中插入已删除的id

时间:2014-01-10 03:09:25

标签: sql sql-server-2008

我有一个表格格式如下:

表名:PartAtt

我在PartAtt中

Id   |   Type   |  Name
-----------------------
1    |    2     |   Bed
2    |    7     |   Bed
3    |    6     |   Sofa
4    |    5     |   Chair
5    |    2     |   Bed
6    |    8     |   Chair
7    |    2     |   Bed

所以我的问题是我不能在这个表上有多个类型的id具有相同的名称(我需要清理它),所以我需要保留最大的id然后转储坏的id的id临时表以及保存的id的id。例如:

清理桌子后,我应该这样:

Table PartAtt                       #tempTable
    Id   |   Type   |  Name         Id    |   updateId
    -----------------------        --------------------   
    3    |    6     |   Sofa         1    |     7  
    4    |    5     |   Chair        2    |     7
    6    |    8     |   Chair        5    |     7
    7    |    2     |   Bed

到目前为止,我能够做的是找到加倍到临时表中的项目“

CREATE TABLE #tempTable(
 Type int,
 Name varcahar(500)
 )

INSERT INTO #tempTable (Type, Name)
    SELECT Type,Name
        FROM PartAtt
     GROUP BY Type,Name
  HAVING COUNT(Name) > 1 && COUNT(Type) > 1     

我使用它来了解哪些项目存在问题,但我无法弄清楚如何删除两次最早的记录(类型和名称)并将它们插入临时表中。

我希望得到一些建议和指示。

2 个答案:

答案 0 :(得分:2)

尝试以下SQL:

备份表

CREATE TABLE deleted_PartAtt(Id int, updateId int, Name char(10));

备份要删除的重复行

INSERT INTO deleted_PartAtt SELECT DISTINCT t1.Id, '', t1.Name FROM PartAtt t1
INNER JOIN PartAtt t2
ON t1.Type = t2.Type AND t1.Name = t2.Name AND t1.Id < t2.Id;


UPDATE dp SET dp.updateId = a.Id FROM deleted_PartAtt dp INNER JOIN (SELECT max(t1.Id) AS Id, t1.Name FROM PartAtt t1 INNER JOIN deleted_PartAtt t2
ON t1.Name = t2.Name GROUP BY t1.Name) a ON a.Name = dp.Name;

删除重复的行

DELETE t1 FROM PartAtt t1
INNER JOIN PartAtt t2
ON t1.Type = t2.Type AND t1.Name = t2.Name AND t1.Id < t2.Id;

SQL Fiddle

答案 1 :(得分:1)

Row_number将成为你今晚的朋友。

通过按名称分区,您可以为每个重复项目分配一个递增的数字。然后保留Row = 1的项目并转储其余项目。

保留这些:

select * from 
(
    select *, 
           ROW_NUMBER() over (partition by Name order by ID DESC) as Row
    from PartAtt
) as Temp
where Row = 1

转储这些:

select * from 
(
    select *,
           ROW_NUMBER() over (partition by Name order by ID DESC) as Row 
    from PartAtt
) as Temp
where Row != 1