I have table of items, every one has it’s start time and end time.
For example:
| id | item | start | end |
+---------+------+------------+------------+
| 2703 | 223 | 2003-12-30 | 2004-01-16 |
| 47029 | 223 | 2004-04-21 | 2005-01-06 |
| 1386593 | 223 | 2005-04-19 | 2005-04-19 |
| 1386739 | 223 | 2005-04-19 | 2006-12-07 |
| 1432862 | 223 | 2006-02-08 | 2006-02-10 |
I’d like to find gaps between items (days between one’s end with next start). Gap between first two items in example is 93 days, between last 2 there is overlap 302 days, which is counted as zero. So gaps for example table are:
96
103
0
0
My goal is to find average gap (49.75 in this example) or other-words sum of gap days (199).
Optional goals to have: min gap (0) and max gap (103).
My solution for now is iterate over rows and calculate it outside database, but i am looking for prompt solution (inside MySQL). I looked over the aggregate functions but don’t have no idea is this possible or not. How is the best way to find such average gap?
SQL Fiddle Example