【发布时间】:2012-06-25 09:22:01
【问题描述】:
我有一张表,表示产品的使用情况,有点像日志。产品使用记录为多个时间戳,我想使用时间范围表示相同的数据。
看起来像这样(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
我想折叠与上一次运行时间差小于 delta(例如:2 秒)的行,并获取开始时间和结束时间,像这样:
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
请注意,如果同一产品的连续使用时间间隔超过 delta(在本例中为 2 秒),则会将它们分成两行。
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')
;
【问题讨论】:
标签: sql postgresql