I have a SQLite Database with a table called “events”, it has the following structure:
rowid ID startTimestamp endTimestamp
1 00:50:c2:63:10:1a 1000 1010
2 00:50:c2:63:10:1a 1100 1030
3 00:50:c2:63:10:1a 1090 1110
4 00:50:c2:63:10:1a 1210 1310
.
.
.
It’s no problem to calculate the average time between startTimestamp and endTimestamp:
SELECT ID, avg(endTimestamp - startTimestamp) AS duration FROM events WHERE senderID ="00:50:c2:63:10:1a"
But now i want to have the average differences between the endTime and the startTime between one row and the following row, that means for my example:
1100-1010 = 90
1090-1030 = 60
1210-1110 = 100
Sum of differences = 90 + 60 + 100 = 250
Average Difference = 250 / 3 = 83,33
Is there a way to do this with an SQL Query? Or should is it necessary to write a piece of code in PHP?
Tested at SQL-Fiddle: test-1 (thanks to @bonCodigo for that)
Since the
MIN(endtimestamp)may not be the one with lowestrowid, the above query needs a correction: