2016-06-22 70 views
1

我有表像下面的格式,除了最大記錄刪除上的重複

Item_Txn  Item_Name 
101   Mouse 
102   Mouse 
103   Mouse 
104   Keyboard 
105   CPU 
106   Monitor 
107   Monitor 

我想刪除除最大Item_Txn重複的項目。例如,鼠標是重複的項目(3次)。我想刪除除(103,鼠標)之外的鼠標記錄。

+0

這叫做DeDup。您還可以在網上找到大量技術。 –

+0

[T-SQL:刪除所有重複的行但保留一個]的可能的重複(http://stackoverflow.com/questions/6025367/t-sql-deleting-all-duplicate-rows-but-keeping-one) –

回答

2
DELETE a 
FROM my_table a 
WHERE EXISTS (SELECT * 
       FROM my_table b 
       WHERE a.Item_Name = b.Item_Name 
       AND b.Item_Txn > a.Item_Txn); 
1

試試這個:

DELETE FROM MyTable 
WHERE Item_Txn IN (
    SELECT K.Item_Txn 
    FROM (SELECT Item_Txn , 
         ROW_NUMBER() OVER (PARTITION BY Item_Name ORDER BY Item_Txn DESC) AS RN 
       FROM  MyTable 
      ) AS K 
    WHERE K.RN > 1); 
4

對於SQL Server 2008和更高:

;WITH cte AS 
(
    SELECT  Item_Txn, Item_Name, 
       ROW_NUMBER() OVER (PARTITION BY Item_Name ORDER BY Item_Txn DESC) AS RowNumber 
    FROM  my_table 
) 

DELETE FROM cte 
    WHERE RowNumber > 1 
1

試試這個,

delete from table 
where Item_Txn not in 
     (select max(Item_Txn) from table group by Item_Name) 
1
DELETE t 
FROM YourTable t 
OUTER APPLY (
    SELECT MAX(Item_Txn) as Item_Txn 
    FROM YourTable t1 
    WHERE t1.Item_Name = t.Item_Name 
    ) as p 
WHERE p.Item_Txn != t.Item_Txn 

查詢將只留下:

103 Mouse 
104 Keyboard 
105 CPU 
107 Monitor 
1

你可以使用中間的子查詢

DELETE FROM `table` 
    WHERE id NOT IN (
     SELECT id 
     FROM (
     SELECT id 
     FROM `table` 
     ORDER BY id DESC 
     LIMIT 1 -- keep this many records 
    ) foo 
    ); 

以上是MySQL的

這是SQL做

DELETE FROM chat WHERE id NOT IN 
     (SELECT TOP 50 id FROM chat ORDER BY id DESC) 
1
;WITH CTE AS 
    (
     SELECT MAX(Item_Txn)Item_Txn, Item_Name FROM ITEM GROUP BY Item_Name 
    ) 
    DELETE t 
    FROM ITEM t 
    WHERE EXISTS 
    (
     SELECT 1 FROM CTE WHERE t.Item_Name = CTE.Item_Name AND t.Item_Txn <> CTE.Item_Txn 
    )