SQL server multi-field deduplication keeps a record

1. Purpose:

Delete duplicate data in some fields and keep one of the record data

2. Effect picture:

Before processing:
Insert picture description here

After processing:
Insert picture description here

3,SQL

delete FROM Atable WHERE EXISTS (
	SELECT id FROM( SELECT name, code FROM Atable GROUP BY name, code HAVING COUNT ( * ) > 1 ) tableabc 
	WHERE Atable.name= tableabc.name AND Atable.code= tableabc.code ) 
AND id NOT IN (
	    SELECT MIN(id) FROM Atable GROUP BY name,code HAVINGCOUNT ( * ) > 1)

Explanation : Extract the duplicate data of the Atable table, as a temporary table tableabc, join tableabc and Atable to extract the duplicated part, and only keep the record data with the smallest id in the duplicate data.

Guess you like

Origin blog.csdn.net/qq_36636312/article/details/110137576