-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-duplicate-rows.sql
96 lines (77 loc) · 1.63 KB
/
remove-duplicate-rows.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
USE TestDB
GO
-- Total rows in the table
SELECT
COUNT(*) AS TotalRows
FROM
dbo.DuplicateData
-- USING DISTINCT
-- Total number of different rows in the table
SELECT
COUNT(DISTINCT CustomerName) AS TotalUniqueCustomers
FROM
dbo.DuplicateData
-- A temporary table as copy of the actual table.
SELECT
*
INTO #DuplicateData
FROM
dbo.DuplicateData
ORDER BY
CustomerName
-- USING GROUP BY AND HAVING TO CHECK FOR DUPLICATES
-- Filter our groups to show records that have a count of more than one
SELECT
CustomerName
, COUNT(*) NameCount
FROM
dbo.#DuplicateData
GROUP BY
CustomerName
HAVING
COUNT(*) > 1
-- Non duplicates
SELECT
DISTINCT *
INTO #NonDuplicateData
FROM
dbo.DuplicateData
ORDER BY
CustomerName
SELECT * FROM #NonDuplicateData ORDER BY CustomerName
-- Truncate the table with the duplicates
TRUNCATE TABLE #DuplicateData
-- Insert unique rows to the table
INSERT INTO #DuplicateData
SELECT * FROM #NonDuplicateData
--Check for duplicates
SELECT * FROM #DuplicateData ORDER BY CustomerName
-- Check for duplicates using ROW_NUMBER window function
SELECT
CustomerName
, ROW_NUMBER() OVER(PARTITION BY CustomerName ORDER BY CustomerName ASC) AS rn
FROM
DuplicateData;
-- Create the CTE, and DELETE the ones greater than one.
WITH Duplicates
AS
(
SELECT
CustomerName
, ROW_NUMBER() OVER(PARTITION BY CustomerName ORDER BY CustomerName ASC) AS rn
FROM
DuplicateData
)
DELETE
FROM
Duplicates
WHERE
rn > 1;
-- Check for duplicates again
SELECT
CustomerName
, ROW_NUMBER() OVER(PARTITION BY CustomerName ORDER BY CustomerName ASC) AS rn
FROM
DuplicateData
-- Housekeeping
DROP TABLE #DuplicateData, #NonDuplicateData