通过SQL Server使用分区删除重复项

时间:2012-02-03 01:15:46

标签: sql sql-server sql-server-2008

我需要从表中删除重复项:

;WITH cte as(
SELECT ROW_NUMBER() OVER (PARTITION BY [specimen id]
                                       ORDER BY ( SELECT 0 ) ) RN
         FROM   quicklabdump)
        delete from cte where RN>1

quicklabdumpID是主键。

我想知道如何只保留quicklabdumpID多次出现的最大[specimen id]

2 个答案:

答案 0 :(得分:17)

将订单更改为quicklabdumpid DESC

WITH cte as(
  SELECT ROW_NUMBER() OVER (PARTITION BY [specimen id]
                            ORDER BY  quicklabdumpid DESC ) RN
  FROM   quicklabdump)
delete from cte where RN>1

答案 1 :(得分:5)

无需分区

delete q
  from quicklabdump q
  where exists
  (
    select *
      from quicklabdump q2
      where q2.[specimen id] = q.[specimen id] and
        q2.quicklabdumpID > q.quicklabdumpID
  )