使用SQL Server 2008 R2删除重复ID和值ROW

时间:2012-12-07 21:57:16

标签: sql sql-server-2008-r2 duplicate-removal

在SQL Server 2008 R2中,我在表格中添加了两个重复的ID和记录。当我尝试删除最后两个记录中的一个时,我收到以下错误。

  

更新或删除的行值不会使该行唯一,也不会改变多行。

数据是:

7   ABC         6
7   ABC         6
7   ABC         6
8   XYZ         1
8   XYZ         1
8   XYZ         4
7   ABC         6
7   ABC         6

我需要删除最后两条记录:

7   ABC         6
7   ABC         6

我一直在尝试使用功能删除最后2条记录"编辑前200行"要删除此重复的ID,但会收到上述错误。

感谢任何帮助。在此先感谢:)

2 个答案:

答案 0 :(得分:1)

由于您没有给出表中其他列的任何线索,假设您的数据位于A,B,C三列中,您可以使用以下命令删除2行:

;with t as (
    select top(2) *
      from tbl
     where A = 7 and B = 'ABC' and C = 6
)
DELETE t;

这将根据条件任意匹配两行,并删除它们。

答案 1 :(得分:0)

这是我用来删除表中可能有很多重复项的重复代码的大纲。

/* I always put the rollback and commit up here in comments until I am sure I have 
   done what I wanted. */
BEGIN tran Jim1 -- rollback tran Jim1 -- Commit tran Jim1; DROP table PnLTest.dbo.What_Jim_Deleted

/* This creates a table to put the deleted rows in just in case I'm really screwed up */
SELECT top 1 *, NULL dupflag 
  INTO jt1.dbo.What_Jim_Deleted --DROP TABLE jt1.dbo.What_Jim_Deleted
  FROM jt1.dbo.tab1;
/* This removes the row without removing the table */
TRUNCATE TABLE jt1.dbo.What_Jim_Deleted;

/* the cte assigns a row number to each unique security for each day, dups will have a
   rownumber > 1.  The fields in the partition by are from the composite key for the 
   table (if one exists.  These are the queries that I ran to show them as dups

SELECT compkey1, compkey2, compkey3, compkey4, COUNT(*) 
  FROM jt1.dbo.tab1
  GROUP BY compkey1, compkey2, compkey3, compkey4
  HAVING COUNT(*) > 1
  ORDER BY 1 DESC


*/
with getthedups as
  (SELECT *,
       ROW_NUMBER() OVER 
         (partition by compkey1,compkey2, compkey3, compkey4 
                          ORDER BY Timestamp desc) dupflag /*This can be anything that gives some order to the rows (even if order doesn't matter) */
     FROM jt1.dbo.tab1)
/* This delete is deleting from the cte which cascades to the underlying table 
   The Where is part of the Delete (even though it comes after the OUTPUT.  The
   OUTPUT takes all of the DELETED row and inserts them into the "oh shit" table,
   just in case.*/
DELETE 
  FROM getthedups 
  OUTPUT DELETED.* INTO jti.dbo.What_Jim_Deleted
  WHERE dupflag > 1

--Check the resulting tables here to ensure that you did what you think you did

/* If all has gone well then commit the tran and drop the "oh shit" table, or let it 
   hang around for a while. */