从表格中选择时间戳在一个小时内的项目

时间:2011-07-15 15:59:13

标签: sql postgresql

我正在使用postgres(postgis),我想执行一个查询,返回所有在一小时内有时间戳的行。

SQL语句会是什么样的?

表格如下:

  • id {integer}
  • name {character varying}
  • 时间戳{带时区的时间戳}

    id   name       timestamp
    ---+----------+--------------------------------
    1    one        "2010-09-24 21:10:39.515+00"
    2    two        "2010-09-16 09:21:09.362+00"
    3    three      "2010-07-08 00:00:46.549+00"
    

编辑#1

这是一个更好的例子。 (在Tometzky的帮助下)所有结果都在1小时之内。也就是说,每行都会给我1小时内的其他行:

select * from myTable order by t

 id |               t               
----+-------------------------------
  9 | 2011-07-15 18:20:20.05+02
 10 | 2011-07-15 19:05:00.05+02
 11 | 2011-07-15 19:40:20.05+02
 13 | 2011-07-15 20:31:01.05+02
 14 | 2011-07-15 20:35:11.05+02
(5 rows)

result of needed query:

 id |  matchid |  origTime                  | matchTime
----+----------+----------------------------+------------------------------
  9 |   10     | 2011-07-15 18:20:20.05+02  | 2011-07-15 19:05:00.05+02
 10 |    9     | 2011-07-15 19:05:00.05+02  | 2011-07-15 18:20:20.05+02
 10 |   11     | 2011-07-15 19:05:00.05+02  | 2011-07-15 19:40:20.05+02
 11 |   10     | 2011-07-15 19:40:20.05+02  | 2011-07-15 19:05:00.05+02
 11 |   13     | 2011-07-15 19:40:20.05+02  | 2011-07-15 20:31:01.05+02
 11 |   14     | 2011-07-15 19:40:20.05+02  | 2011-07-15 20:35:11.05+02
 13 |   11     | 2011-07-15 20:31:01.05+02  | 2011-07-15 19:40:20.05+02
 13 |   14     | 2011-07-15 20:31:01.05+02  | 2011-07-15 20:35:11.05+02
 14 |   11     | 2011-07-15 20:35:11.05+02  | 2011-07-15 19:40:20.05+02
 14 |   13     | 2011-07-15 20:35:11.05+02  | 2011-07-15 20:31:01.05+02
(10 rows)

2 个答案:

答案 0 :(得分:3)

select 
    t0.id, t1.id as matchid, 
    t0.ts as origTime, t1.ts as matchTime
from t t0
inner join t t1 on 
    t1.ts between 
        t0.ts - interval '1 hour'
        and 
        t0.ts + interval '1 hour'
    and t0.id != t1.id
;

答案 1 :(得分:1)

这样的事情:

$ select * from test;
 id |               t               
----+-------------------------------
  9 | 2011-07-15 18:31:01.059487+02
 10 | 2011-07-15 18:31:01.55044+02
 11 | 2011-07-15 18:31:01.850583+02
 12 | 2011-07-15 18:31:02.064435+02
 13 | 2011-07-15 18:31:02.333449+02
 14 | 2011-07-15 18:31:02.727461+02
 15 | 2011-07-15 18:31:03.279447+02
 16 | 2011-07-15 18:31:03.642454+02
 17 | 2011-07-15 18:33:34.910252+02
 18 | 2011-07-15 18:33:35.995455+02
 19 | 2011-07-15 18:33:36.45246+02
(11 rows)

$ select id, lastid
  from (
    select id,
    t-lag(t) over (order by t) as lag,
    lag(id) over (order by t) as lastid from test
  ) as _
  where lag < '1 second';
 id | lastid 
----+--------
 10 |      9
 11 |     10
 12 |     11
 13 |     12
 14 |     13
 15 |     14
 16 |     15
 19 |     18
(8 rows)