-
Notifications
You must be signed in to change notification settings - Fork 4
/
00613-shortest-distance-in-a-line.sql
43 lines (31 loc) · 1.7 KB
/
00613-shortest-distance-in-a-line.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
-- cross joining all the points from 2 tables, except the ones where they are same
-- find the min of absolute distance
select min(abs(a - b)) as shortest
from
(select p1.x as a, p2.x as b
from Point p1 cross join Point p2
where p1.x != p2.x) temp
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- concise version of the above
select min(abs(p1.x - p2.x)) as shortest
from Point p1 cross join Point p2
where p1.x != p2.x
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- pull min distance with a where condition
select min(p1.x - p2.x) as shortest
from Point p1, Point p2
where p1.x > p2.x
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- sort the table, and do lag. Now diff between current and lag- because difference between the sorted will always be lesser than difference between the larger ones
-- pull the min distance
with CTE as
(select x - lag(x) over(order by x) as distance
from Point)
select min(distance) as shortest from CTE
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- picking the lowest distance, 1st row will always be null hence use offset
select x - lag(x) over(order by x) as shortest
from Point
order by 1 asc
limit 1 offset 1
-- no companies listed