In BigQuery, I'm trying to write a query that calculates the distance between the start and end date for each ID. I'm not interested in the points between those date ranges. I only need to grab the lat/long of the start and end date and calculate the euclidean distance.
Table 1 looks like this:
ID startdate enddate
A 2016-9-16 2016-10-9
A 2017-3-18 2017-4-9
Table 2 has the coordinates and looks like this:
ID Date Latitude Longitude
A 2016-9-16 40.76 -109.33
A 2016-9-17 40.72 -109.33
A 2016-10-9 40.75 -109.33
A 2017-3-18 40.81 -109.33
A 2017-4-8 40.83 -109.33
A 2017-4-9 40.96 -109.32
My desired results would look like:
ID t1.startdate t2.Latitude t2.Longitude t1.enddate t2.Latitude t2.Longitude distance
A 2017-3-18 40.81 -109.33 2017-4-9 40.96 -109.32 150
A 2016-9-16 40.76 -109.33 2016-10-9 40.75 -109.33 200
This is as close as I've gotten but since there can be multiple ID's, it's not matching the correct start and end dates for each ID:
SELECT
t1,t2,
ST_DISTANCE(Point1, Point2 ) as distance
from (
SELECT
ID,
st_geogpoint(Longitude,Latitude) as Point1
from `t2` AS t2 INNER JOIN
`t1` AS t1 ON t1.ID = t2.ID
WHERE t1.ID = t2.ID AND
t2.Date = t1.startdate ) t1,
(
SELECT
ID,
st_geogpoint(Longitude, Latitude) as Point2
from `t2` AS t2 INNER JOIN
`t1` AS t1 ON t1.ID = t2.ID
WHERE t1.ID = t2.ID AND
t2.Date = t1.enddate
) t2
WHERE t1.ID = t2.ID
Current results look like:
ID t1.startdate t2.Latitude t2.Longitude t1.enddate t2.Latitude t2.Longitude distance
A 2016-9-16 40.76 -109.33 2016-10-9 40.75 -109.33 150
A 2016-9-16 40.76 -109.33 2017-4-9 40.96 -109.32 250
A 2017-3-18 40.81 -109.33 2017-4-9 40.96 -109.32 200
A 2017-3-18 40.81 -109.33 2016-10-9 40.75 -109.33 250