-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path34_identify_reverse_pair_multiple_methods.sql
More file actions
65 lines (51 loc) · 1.24 KB
/
34_identify_reverse_pair_multiple_methods.sql
File metadata and controls
65 lines (51 loc) · 1.24 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
--identify reverse pairs in data
--table
--src_dest table
/*
create table src_dest(
source varchar(50),
destination varchar(50),
distance int
)
insert into src_dest(source,destination,distance)
values('Alaska','Albany',5166),
('Dover','Florida',1393),
('Illinois','Indiana',279),
('New Mexico','New York',2873),
('Albany','Alaska',5166),
('Ohio','Oklahoma',1383),
('Indiana','Illinois',279),
('Oklahoma','Ohio',1383),
('Frankfort','Georgia',695),
('Georgia','Frankfort',695)
*/
select * from src_dest
--method 1
--using self join and except
--case when you dont have to modify the base table
select * from src_dest
except
select s.*
from src_dest s
join src_dest d
on (s.source = d.destination
and s.destination = d.source
and s.source > s.destination)
--method 2
select distinct route_src_dest,distance
from
(
select case when source > destination then concat(source,'-',destination)
when source < destination then concat(destination,'-',source)
end as route_src_dest
,distance
from src_dest
)a
--method 3
--modify the base table (parent table)
select s.*
from src_dest s
join src_dest d
on (s.source = d.destination
and s.destination = d.source
and s.source > s.destination)