For formulas that are more complex than a simple summation, you must calculate the actual difference values ββfor each record by looking at the corresponding start points, for example:
SELECT (SELECT MIN(startTimestamp) FROM table1 AS next WHERE next.startTimestamp > table1.startTimestamp AND ID = '...' ) - endTimestamp AS timeDifference FROM table1 WHERE nextStartTimestamp IS NOT NULL AND ID = '...'
Then you can use all the difference values ββto perform the calculations:
SELECT SUM(timeDifference) / COUNT(*) AS average, AVG(timeDifference) AS moreEfficientAverage, SUM(timeDifference * timeDifference) / COUNT(*) - AVG(timeDifference) * AVG(timeDifference) AS variance FROM (SELECT (SELECT MIN(startTimestamp) FROM table1 AS next WHERE next.startTimestamp > table1.startTimestamp AND next.ID = '...' ) - endTimestamp AS timeDifference FROM table1 WHERE nextStartTimestamp IS NOT NULL AND ID = '...')
source share