Thursday, December 16, 2010

HOW TO DELETE DUPLICATE VALUES IN MSSQL


/* Create Table with 7 entries - 3 are duplicate entries */
CREATE TABLE Duplicate_TABLE (COLUMN1 INT, COLUMN2 INT)
INSERT INTO Duplicate_TABLE
SELECT 1, 1
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4
GO

/* It should give you 7 rows */
SELECT * FROM Duplicate_TABLE
GO



/* Delete Duplicate records */
WITH CTE (COLUMN1,COLUMN2, DuplicateCount)
AS
(
SELECT COLUMN1,COLUMN2,
ROW_NUMBER() OVER(PARTITION BY COLUMN1,COLUMN2 ORDER BY COLUMN1) AS DuplicateCount
FROM Duplicate_TABLE
)
DELETE
FROM CTE
WHERE DuplicateCount > 1
GO
/* It should give you Distinct 4 records */
SELECT * FROM Duplicate_TABLE
GO


No comments:

Post a Comment