Delete duplicate records only on condition in sql server

你。 提交于 2020-02-06 10:00:31

问题


I want to delete duplicates for example I want to delete this row "Test2, 321, 0" because there is a duplicate, but in row 1 and 2 I only want to delete row two because the type id is higher then the current duplicate in row one.

This is my table

ID, Name, RecordNum, Type
--------------------------
1, Test, 123, 0
2, Test, 123, 1
3, Test2, 321, 0
4, Test2, 321, 0

I can delete duplicate in row 4 using this query. but I cannot seem to figure out how to delete row 2 because row 1 is the same but type number is lower. and if the type number is 2 it wins and you have to delete any duplicates with 0 and 1 type numbers that have the same name and recordnum.

WITH dup2 as ( 
  SELECT Name
       , RecordNum
       , Type ROW_NUMBER() OVER(PARTITION BY Name, RecordNum, Type ORDER BY ID ASC) AS NumOfDups 
    FROM MyTbale) 
  delete FROM dup2 WHERE NumOfDups > 1

回答1:


So basically you want to keep only one record for each Name, RecordNum group. If the Type is the same keep only the lowest ID, if the Type is different keep the lowest type:

WITH dup2 AS 
( 
         SELECT  NAME, 
                 RecordNum, 
                 NumOfDups = ROW_NUMBER()OVER(
                                 PARTITION BY NAME, RecordNum 
                                 ORDER BY CASE WHEN Type=2 THEN 0 ELSE 1 END, Type, Id)
         FROM    MyTbale) 
DELETE 
FROM   dup2 
WHERE  NumOfDups > 1

SQL-Fiddle Demo

Edited according to comment: "Let say when the type = 2 then I want to delete the other matching records that have a zero or one for type, so two wins here."



来源:https://stackoverflow.com/questions/26474241/delete-duplicate-records-only-on-condition-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!