【问题标题】:Select the latest date, from dates that differ from each other by no more than x minutes从彼此相差不超过 x 分钟的日期中选择最晚的日期
【发布时间】:2018-01-07 18:09:00
【问题描述】:

我有两个问题,我实际上是在 Postgres 中处理一些数据(但如果你可以在 MySQL 中解决它,它也会有所帮助),此时我需要做这些事情:

  1. 组日期彼此相差不超过 x 分钟(例如 15 分钟)

  2. 从我们在上一步中获得的每一组日期中选择最新的一个。 (我想我可以自己解决这个问题;]),但我们将不胜感激。

我希望我把我想做的事情写得很清楚:)

我正在寻找一些解决我的问题的方法,但是我发现了很多关于按天或分钟分组日期的问题和答案,但这不是我想要的,而且对任何方式都没有帮助 :)

示例日期:

2016-10-15 11:29:06+02:00
2016-10-15 11:29:09+02:00
2016-10-15 11:29:15+02:00
2016-10-15 11:29:24+02:00
2016-10-15 12:41:11+02:00
2016-10-15 12:41:13+02:00
2016-10-15 12:41:15+02:00
2016-10-15 12:41:17+02:00
2016-10-15 12:41:28+02:00
2016-10-15 13:51:04+02:00
2016-10-15 13:51:07+02:00
2016-10-15 13:51:09+02:00
2016-10-15 13:51:11+02:00
2016-10-15 13:51:17+02:00
2016-10-15 13:51:19+02:00
2016-10-15 13:51:21+02:00
2016-10-15 13:51:25+02:00
2016-10-15 13:51:28+02:00
2016-10-15 13:51:29+02:00
2016-10-15 13:51:30+02:00
2016-10-15 15:12:02+02:00
2016-10-15 15:12:03+02:00
2016-10-15 15:12:04+02:00
2016-10-15 15:12:07+02:00
2016-10-15 15:12:09+02:00
2016-10-15 15:12:11+02:00
2016-10-15 15:12:13+02:00
2016-10-15 15:12:14+02:00
2016-10-15 15:12:17+02:00
2016-10-15 15:12:21+02:00
2016-10-15 15:12:23+02:00
2016-10-15 15:12:25+02:00
2016-10-15 16:31:00+02:00
2016-10-15 16:31:02+02:00
2016-10-15 16:31:03+02:00
2016-10-15 16:31:05+02:00
2016-10-15 16:31:07+02:00
2016-10-15 16:31:09+02:00
2016-10-15 16:31:11+02:00
2016-10-15 16:31:13+02:00
2016-10-15 16:31:15+02:00
2016-10-15 16:31:16+02:00
2016-10-15 16:31:19+02:00
2016-10-15 16:31:22+02:00
2016-10-15 17:50:05+02:00
2016-10-15 17:50:06+02:00
2016-10-15 17:50:07+02:00
2016-10-15 17:50:12+02:00
2016-10-15 17:50:17+02:00
2016-10-15 17:50:26+02:00
2016-10-15 17:50:37+02:00
2016-10-15 17:50:41+02:00
2016-10-19 12:13:23+02:00
2016-10-19 12:13:33+02:00
2016-10-19 12:13:42+02:00
2016-10-19 13:39:55+02:00
2016-10-19 13:40:05+02:00

预期结果(类似):

2016-10-15 11:29:24+02:00
2016-10-15 12:41:28+02:00
2016-10-15 13:51:30+02:00
2016-10-15 15:12:25+02:00
2016-10-15 16:31:22+02:00
2016-10-15 17:50:41+02:00
2016-10-19 12:13:42+02:00
2016-10-19 13:40:05+02:00

【问题讨论】:

  • “postgis”,我假设你的意思是 Postgres。
  • @GordonLinoff 是的,当然! :)
  • 有一个编辑按钮

标签: mysql sql postgresql timestamp


【解决方案1】:

您想要的是距离 下一个 日期超过 15 分钟的日期列表。这在 Postgres 中最容易解决:

select t.*
from (select t.*, lead(dte) over (order by dte) as next_dte
      from t
     ) t
where next_dte is NULL or next_dte > dte + interval '15 minute';

在任一数据库中,您也可以使用 not exists 执行此操作:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.dte > t.dte and t2.dte < date_add(t.dte, interval 15 minute)
                 );

我在这个版本中使用 MySQL 语法进行日期运算。

【讨论】:

  • 它就像一个魅力!完美!非常感谢戈登! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多