gpt4 book ai didi

sql - 从表中选择时间戳彼此相差不到一小时的项目

转载 作者:行者123 更新时间:2023-11-29 11:43:57 25 4
gpt4 key购买 nike

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

SQL 语句会是什么样子?

表格如下所示:

  • id { 整数}
  • 名字{字符变化}
  • 时间戳{带时区的时间戳}

    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)

最佳答案

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
;

关于sql - 从表中选择时间戳彼此相差不到一小时的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com