如何删除除SQL Server中的一个以外的所有重复记录

时间:2017-03-17 13:25:53

标签: sql-server

我尝试删除没有单个

的多条记录

输入:

    Id  Temp           P_TempId
    ------------------------------------
    AN  #1001#.Test    5001,8001
    AN  #1001#.Test    5001,8001
    AN  #1002#.Test    5001,4001,7001,8001
    AN  #1002#.Test    5001,4001,7001,8001
    AN  #1002#.Test    5001,4001,7001,8001

输出:

        Id  Temp        P_TempId
        ---------------------------------------
        AN  #1001#.Test 5001,8001
        AN  #1002#.Test 5001,4001,7001,8001

1 个答案:

答案 0 :(得分:2)

使用common table expression row_number() 对每组Id_Temp, P_TempId进行编号,并删除编号大于1的编号。

;with cte as (
  select   
      *
    , rn = row_number() over (
            partition by Id, Temp, P_TempId
            order by (select 1)
            )
    from t
)
delete 
  from cte 
  where cte.rn > 1 

或没有cte,改为使用标准子查询:

  delete s
  from (
    select   
        *
      , rn = row_number() over (
              partition by Id, Temp, P_TempId
              order by (select 1)
              )
    from t
    ) as s
  where s.rn > 1 

rextester演示:http://rextester.com/CWO44915

返回:

+----+-------------+---------------------+
| Id |    Temp     |      P_TempId       |
+----+-------------+---------------------+
| AN | #1001#.Test | 5001,8001           |
| AN | #1002#.Test | 5001,4001,7001,8001 |
+----+-------------+---------------------+