-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path96_delete_duplicate_data_from_parent(master)_table-4 methods.sql
105 lines (83 loc) · 1.87 KB
/
96_delete_duplicate_data_from_parent(master)_table-4 methods.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
97
98
99
100
101
102
103
104
105
use int_ques;
/*
CREATE TABLE employee_duplicate
(
[ID] INT identity(1,1),
[FirstName] Varchar(100),
[LastName] Varchar(100),
[Country] Varchar(100),
)
GO
Insert into employee_duplicate ([FirstName],[LastName],[Country] )
values('Raj','Gupta','India'),
('Raj','Gupta','India'),
('Mohan','Kumar','USA'),
('James','Barry','UK'),
('James','Barry','UK'),
('James','Barry','UK')
*/
select * from employee_duplicate
--method_1
--using group by and count
--duplicate data
select firstname,
lastname,
country,
count(1) as n
from employee_duplicate
group by firstname,
lastname,
country
having count(1) > 1
--method 2
--using aggregate function
delete from employee_duplicate
where id not in (
select --firstname,
--lastname,
--country,
max(id) --as id
from employee_duplicate
group by firstname,
lastname,
country
)
select * from employee_duplicate
--delete all records from the table and reload it with all data
delete from employee_duplicate
--run insert into statement again
--method 3
--using cte
with cte1 as
(
select firstname,
lastname,
country,
row_number() over(partition by firstname, lastname, country order by id asc) new_id
from employee_duplicate
)
--select * from cte1
delete from cte1
where new_id > 1;
select * from employee_duplicate
--delete all records from the table and reload it with all data
delete from employee_duplicate
--run insert into statement again
--method 4
--using rank function and inner join
/*
select t.*,
r.new_id
*/
delete t
from employee_duplicate t
inner join (
select id,
firstname,
lastname,
country,
rank() over(partition by firstname, lastname, country order by id asc) new_id
from employee_duplicate
) r on t.id = r.id
where r.new_id > 1;
select * from employee_duplicate;