删除“重复”记录

时间:2014-02-17 14:00:40

标签: sql sql-server

问题:我不知道如何删除所有“重复”记录,以便只留下不同的记录。

所以从这个:

╔══════╦════════════╦════════╦════╗
║ date ║ dupe_count ║ field1 ║ id ║
╠══════╬════════════╬════════╬════╣
║ x    ║         48 ║ y      ║ a  ║
║ x    ║         48 ║ y      ║ b  ║
║ x    ║         48 ║ y      ║ c  ║
║ x    ║         48 ║ y      ║ d  ║
║ x    ║         48 ║ y      ║ e  ║
║ x    ║         48 ║ y      ║ f  ║
║ x    ║         48 ║ y      ║ g  ║
║ x    ║         48 ║ y      ║ h  ║
║ x    ║         48 ║ y      ║ i  ║
╚══════╩════════════╩════════╩════╝

对此:

╔══════╦════════════╦════════╦════╗
║ date ║ dupe_count ║ field1 ║ id ║
╠══════╬════════════╬════════╬════╣
║ x    ║          1 ║ y      ║ a  ║
╚══════╩════════════╩════════╩════╝

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

SQL Server具有可更新CTE的优点。所以,你可以这样做:

with todelete as (
      select t.*, row_number() over (partition by dupe_count, field1 order by id) as seqnum
      from table t
     )
delete from todelete
    where seqnum > 1;