+ 2
This will need to be done in steps. First find the duplicate records in your table having a count > 1. Next insert those duplicates into a temp table. Next delete all of the duplicate records from your table, finally insert the rows from the temp table back into your table. Run the below to see this in action using temp tables (run in steps and select * from each table at any time). CREATE TABLE #NAMES(LastName varchar(25), FirstName varchar(25), Record_Description varchar(100)) INSERT INTO #NAMES VALUES ('Smith', 'John', '5 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'John', '5 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'John', '5 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'John', '5 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'John', '5 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'Jane', '3 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'Jane', '3 Original Duplicates') INSERT INTO #NAMES VALUES ('Smith', 'Jane', '3 Original Duplicates') INSERT INTO #NAMES VALUES ('Doe', 'John', '2 Original Duplicates') INSERT INTO #NAMES VALUES ('Doe', 'John', '2 Original Duplicates') INSERT INTO #NAMES VALUES ('Jones', 'Bill', '1 Original No Duplicates') --FIND RECORDS HAVING A COUNT > 1 AND INSERT INTO TEMP TABLE SELECT LastName, FirstName, Record_Description, COUNT(*) AS [RECORD_COUNT] INTO #TEMP_DUPLICATES FROM #NAMES GROUP BY LastName, FirstName, Record_Description HAVING count(*) > 1 --DELETE RECORDS FROM SAMPLE TABLE THAT ARE IN TEMP TABLE DELETE #NAMES FROM #NAMES, #TEMP_DUPLICATES WHERE #NAMES.FirstName = #TEMP_DUPLICATES.FirstName AND #NAMES.LastName = #TEMP_DUPLICATES.LastName AND #NAMES.Record_Description = #TEMP_DUPLICATES.Record_Description --INSERT UNIQUE RECORDS FROM TEMP TABLE BACK INTO SAMPLE TABLE INSERT INTO #NAMES SELECT LastName, FirstName, Record_Description FROM #TEMP_DUPLICATES DROP TABLE #TEMP_DUPLICATES --VIEW FINAL RESULTS SELECT * FROM #NAMES DROP TABLE #NAMES
26th Sep 2016, 6:55 PM
Chris G
Chris G - avatar