I have the following table in my postgreSQL 8.3.14 database
timestamp status
2012-03-12 19:15:01 f
2012-03-12 19:15:02 f
2012-03-12 19:15:05 f
2012-03-12 19:17:01 t
-- END OF SLOT ONE (change from f to t)
2012-03-12 19:20:01 f
2012-03-12 19:25:01 f
2012-03-12 19:27:01 f
2012-03-12 20:15:01 t
-- END OF SLOT TWO (change from f to t)
No I want to get the following result:
- slot 1 duration (2012-03-12 19:17:01 – 2012-03-12 19:15:01)
- slot 2 duration (2012-03-12 20:15:01 – 2012-03-12 19:20:01)
So every time the status value changes from f to t, a new slot begins. Now I want to get all slots and the duration of every slot. The timestamp is not every second or minute or so, the difference between two entries is more or less random.
I thought about subqueries and grouping, but I have no idea how to solve this, at least whether it is possible at all. So my question is: is that possible 🙂 And if it is, how to start? I’m stuck because of the f-t changing issue…
If you have a modern version of PG you can do what you want using window functions (in my example instead of timestamps I have integers, but it doesn’t matter):
I’m working on a non-window function version…
Here is the query with window functions:
Here is the version of the query for PG without window functions (it is actually shorter, but less clear)