I have a table representing the use of a product, like a log. Product usage is recorded as multiple timestamps, I want to present the same data using time ranges.
It looks like this (PostgreSQL 9.1):
userid | timestamp | product ------------------------------------- 001 | 2012-04-23 9:12:05 | foo 001 | 2012-04-23 9:12:07 | foo 001 | 2012-04-23 9:12:09 | foo 001 | 2012-04-23 9:12:11 | barbaz 001 | 2012-04-23 9:12:13 | barbaz 001 | 2012-04-23 9:15:00 | barbaz 001 | 2012-04-23 9:15:01 | barbaz 002 | 2012-04-24 3:41:01 | foo 002 | 2012-04-24 3:41:03 | foo
I want to collapse lines whose time difference with the previous run is less than the delta (say: 2 seconds), and get the start time and end time, for example:
userid | begin | end | product ---------------------------------------------------------- 001 | 2012-04-23 9:12:05 | 2012-04-23 9:12:09 | foo 001 | 2012-04-23 9:12:11 | 2012-04-23 9:12:13 | barbaz 001 | 2012-04-23 9:15:00 | 2012-04-23 9:15:01 | barbaz 002 | 2012-04-24 3:41:01 | 2012-04-24 3:41:03 | foo
Note that sequential use of the same product is split into two lines if their use is greater than delta (in this example, 2 seconds).
create table t (userid int, timestamp timestamp, product text); insert into t (userid, timestamp, product) values (001, '2012-04-23 9:12:05', 'foo'), (001, '2012-04-23 9:12:07', 'foo'), (001, '2012-04-23 9:12:09', 'foo'), (001, '2012-04-23 9:12:11', 'barbaz'), (001, '2012-04-23 9:12:13', 'barbaz'), (001, '2012-04-23 9:15:00', 'barbaz'), (001, '2012-04-23 9:15:01', 'barbaz'), (002, '2012-04-24 3:41:01', 'foo'), (002, '2012-04-24 3:41:03', 'foo') ;