-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108_3 methods to delete duplicate data from master table.sql
More file actions
113 lines (86 loc) · 1.75 KB
/
108_3 methods to delete duplicate data from master table.sql
File metadata and controls
113 lines (86 loc) · 1.75 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
-- 3 methods to delete duplicate data from a table
use questions;
--customer table
/*
CREATE TABLE Customer
(
[ID] INT identity(1,1),
[FirstName] Varchar(100),
[LastName] Varchar(100),
[Country] Varchar(100),
)
GO
Insert into Customer ([FirstName],[LastName],[Country] )
values('Raj','Gupta','India'),
('Raj','Gupta','India'),
('Mohan','Kumar','USA'),
('James','Barry','UK'),
('James','Barry','UK'),
('James','Barry','UK')
*/
-- method 1 using count and having cluase
select * from customer;
--found duplicate records
select firstname,
lastname,
country
from customer
group by firstname,
lastname,
country
having count(*) > 1
/*
select * from
customer
where id in (select
max(id) as id
from customer
group by firstname,
lastname,
country)
*/
delete from customer
where id not in (select
max(id) as id
from customer
group by firstname,
lastname,
country)
--truncate table customer
--saving the result in a new table using the into statement
select firstname,
lastname,
country,
max(id) as id
into customer_copy
from customer
group by firstname,
lastname,
country
select * from customer_copy
-- method 2
-- using cte and row_number function
with cte as
(
select id,firstname,
lastname,
country,
row_number() over(partition by firstname,
lastname,
country order by id ) as duplicate_count
from customer
)
delete from cte
where duplicate_count > 1;
--method 3
--using inner join and rank function
delete b
from customer b
inner join
(
select *,
rank() over(partition by firstname, lastname, country order by id) as rnk
from customer
) a
on b.id = a.id
where a.rnk > 1