首页 > 解决方案 > 在Java中将时间戳分组为给定长度的间隔的最佳方法是什么?

问题描述

我在 Oracle DB 中有一个指标表,其中一列是时间戳。我需要从数据库中读取指标,并将它们分组为起始时间戳和结束时间戳之间任意长度的给定间隔(2 个月或 3 小时或 1 天或 2 年等)。时间戳的格式为

2020-05-24T18:51:10.018-07:00

我知道我可以读取表格中的所有条目并将它们排序并通过将它们全部转换为秒来将它们分组为间隔,但是有更好的方法吗?

标签: javasqloraclealgorithmtimestamp

解决方案


你可以用match_recognize这个。

with t(ts) as (
  select
    current_timestamp
    + interval '3' minute
    * dbms_random.value(0, level)
  from dual
  connect by level < 20
)
select *
from t
match_recognize(
  order by ts asc
  measures
    match_number() as grp
  all rows per match
  pattern(a w5min*)
  define
    /*Rows within 5 minutes after the first row in bucket*/
    w5min as ts - first(ts) < interval '5' minute
)
TS | 玻璃钢
:----------------- | --:
2021-11-03 06:20:40 | 1
2021-11-03 06:20:56 | 1
2021-11-03 06:23:27 | 1
2021-11-03 06:23:49 | 1
2021-11-03 06:25:23 | 1
2021-11-03 06:25:36 | 1
2021-11-03 06:32:14 | 2
2021-11-03 06:34:38 | 2
2021-11-03 06:36:29 | 2
2021-11-03 06:36:59 | 2
2021-11-03 06:39:29 | 3
2021-11-03 06:40:17 | 3
2021-11-03 06:41:07 | 3
2021-11-03 06:47:14 | 4
2021-11-03 06:48:31 | 4
2021-11-03 06:52:29 | 5
2021-11-03 06:59:22 | 6
2021-11-03 07:02:05 | 6
2021-11-03 07:04:54 | 7

db<>在这里摆弄


推荐阅读