Reputation: 399
I have a table with Date and latitude, longitude values in each row. I want a sql query to calculate the distance travailed in a day.
Say for date 2013-03-01
I want the total distance traveled,
ID DATE LAT LONG V_ID
---------------------------------------------------
123 2013-03-01 06:05:24 45.544 86.544 1
124 2013-03-01 06:15:17 45.676 86.676 1
125 2013-03-01 06:25:24 46.544 86.544 2
126 2013-03-01 06:38:14 46.651 86.651 2
127 2013-03-02 07:12:04 46.876 86.876 1
128 2013-03-02 10:38:14 46.871 86.871 1
129 2013-03-02 10:56:14 46.871 86.671 2
130 2013-03-02 15:28:02 46.243 86.871 2
To calculate the distance what I wrote a sql function :
CREATE FUNCTION [dbo].[fnCalcDistanceKM](@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END
but I want the total distance traveled in a day and for day 2013-03-01
I have top four row
and I want total distance traveled in 2013-03-01
and similar to this date 2013-03-02
has last four row , how do I calculate distance for these rows.
Upvotes: 3
Views: 1942
Reputation: 9890
You can use self join with ROW_NUMBER()
to get distance travelled like this.
Query
;WITH CTE AS
(
SELECT *,CONVERT(DATE,[Date]) as tday,ROW_NUMBER()OVER(PARTITION BY CONVERT(DATE,[Date]) ORDER BY [Date] ASC) rn
FROM Travel
)
SELECT T1.tday,SUM([dbo].[fnCalcDistanceKM](T1.lat,T2.lat,T1.long,T2.long)) as dist
FROM CTE T1
INNER JOIN CTE T2
ON T1.tday = T2.tday
AND T1.rn = T2.rn -1
GROUP BY T1.tday
Output
| tday | dist |
|------------|--------------------|
| 2013-03-01 | 129.40048639456964 |
| 2013-03-02 | 87.36216677343607 |
Upvotes: 2