2014-01-10 89 views
1

我有以下格式的表ID:刪除的重複記錄並插入另一表中刪除了SQL

表名: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。因此,例如:

清理表後,我應該有這樣的:

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  
項目

我用它來知道哪些項目有問題,但我不能想出如何刪除的(類型和名稱)兩次的最古老的記錄,如上它們插入到一個臨時表。

我將不勝感激一些建議和指針來做到這一點。

+0

我覺得在數據中的一些錯誤提供..牀有型原表中第二排給出「2」但「7」.. – kwelsan

回答

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

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