AdvancedTopic: phase5.sql

File phase5.sql, 1.9 KB (added by 231504, 5 days ago)
Line 
1CREATE EXTENSION IF NOT EXISTS postgis;
2
3ALTER TABLE coordinates
4ADD COLUMN geom GEOGRAPHY(Point, 4326);
5
6UPDATE coordinates
7SET geom = ST_SetSRID(
8 ST_MakePoint(longitude, latitude),
9 4326
10)::geography;
11
12CREATE INDEX idx_coordinates_geom
13ON coordinates
14USING GIST (geom);
15
16--query1
17SELECT
18 h.name AS hotel,
19 a.name AS attraction,
20 ROUND(
21 ST_Distance(hc.geom, ac.geom)
22 ) AS distance_meters
23FROM hotels h
24JOIN locations hl
25 ON h.location_id = hl.id
26JOIN coordinates hc
27 ON hl.coordinate_id = hc.id
28
29JOIN facultatives f
30 ON TRUE
31
32JOIN attractions a
33 ON a.facultative_id = f.id
34
35JOIN locations al
36 ON f.location_id = al.id
37
38JOIN coordinates ac
39 ON al.coordinate_id = ac.id
40
41WHERE h.id = 1
42AND ST_DWithin(
43 hc.geom,
44 ac.geom,
45 5000
46 )
47ORDER BY distance_meters;
48
49
50--query 2
51SELECT DISTINCT ON (h.id)
52 h.id,
53 h.name AS hotel,
54 ap.name AS nearest_airport,
55 ap.code,
56 ROUND(
57 (ST_Distance(hc.geom, ac.geom) / 1000)::numeric,
58 2
59 ) AS distance_km
60FROM hotels h
61
62JOIN locations hl
63 ON h.location_id = hl.id
64JOIN coordinates hc
65 ON hl.coordinate_id = hc.id
66
67CROSS JOIN airports ap
68
69JOIN locations al
70 ON ap.location_id = al.id
71JOIN coordinates ac
72 ON al.coordinate_id = ac.id
73
74ORDER BY
75 h.id,
76 ST_Distance(hc.geom, ac.geom);
77
78
79--query3
80SELECT DISTINCT ON (h.id)
81 h.name AS hotel,
82 ts.name AS nearest_transport_station,
83 ts.station_type,
84 ROUND(
85 (ST_Distance(hc.geom, tc.geom))::numeric,
86 2
87 ) AS distance_meters
88FROM hotels h
89
90JOIN locations hl
91 ON h.location_id = hl.id
92JOIN coordinates hc
93 ON hl.coordinate_id = hc.id
94
95CROSS JOIN transport_stations ts
96
97JOIN locations tl
98 ON ts.location_id = tl.id
99JOIN coordinates tc
100 ON tl.coordinate_id = tc.id
101
102ORDER BY
103 h.id,
104 ST_Distance(hc.geom, tc.geom);