删除重复时的最大记录除外

时间:2016-06-22 12:28:40

标签: sql sql-server

我有以下格式的表格,

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

我想删除除最大Item_Txn之外的重复项目。例如,鼠标是重复项目(3次)。我想删除鼠标记录,除了(103,鼠标)。

7 个答案:

答案 0 :(得分: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 :(得分: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);

答案 2 :(得分: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 );

答案 3 :(得分:1)

试试这个,

delete from table 
where Item_Txn not in
         (select max(Item_Txn) from table group by Item_Name)

答案 4 :(得分: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

答案 5 :(得分: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) 

答案 6 :(得分: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
    )