我在 Oracle DB 中有一個指標表,其中一列是時間戳。我需要從資料庫中讀取指標并將它們分組到開始時間戳和結束時間戳之間的任意長度(2 個月或 3 小時或 1 天或 2 年等)的給定間隔中。時間戳將是格式
2020-05-24T18:51:10.018-07:00
我知道我可以從表中讀取所有條目,并通過將它們全部轉換為秒來對它們進行排序并將它們分組到間隔中,但是有沒有更好的方法來做到這一點?
uj5u.com熱心網友回復:
您可以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<>在這里擺弄
uj5u.com熱心網友回復:
這是否是最好的方法,誰能告訴?如果你想要一個 Java 解決方案,我推薦這個。
OffsetDateTime[] timestamps = {
OffsetDateTime.parse("2020-05-24T18:51:10.018-07:00"),
OffsetDateTime.parse("2020-03-07T23:45:02.399-08:00"),
OffsetDateTime.parse("2020-05-24T20:01:11.442-07:00"),
OffsetDateTime.parse("2020-03-08T01:03:05.079-08:00"),
OffsetDateTime.parse("2020-05-24T19:32:34.461-07:00"),
};
TemporalAmount intervalLength = Duration.ofHours(2);
List<OffsetDateTime> list = new ArrayList<>(Arrays.asList(timestamps));
list.sort(Comparator.naturalOrder());
List<List<OffsetDateTime>> groups = new ArrayList<>();
if (! list.isEmpty()) {
List<OffsetDateTime> currentGroup = new ArrayList<>();
Iterator<OffsetDateTime> itr = list.iterator();
OffsetDateTime first = itr.next();
currentGroup.add(first);
OffsetDateTime groupEnd = first.plus(intervalLength);
while (itr.hasNext()) {
OffsetDateTime current = itr.next();
if (current.isBefore(groupEnd)) {
currentGroup.add(current);
} else { // new group
groups.add(currentGroup);
currentGroup = new ArrayList<>();
groupEnd = current.plus(intervalLength);
currentGroup.add(current);
}
}
// remember to add last group
groups.add(currentGroup);
}
groups.forEach(System.out::println);
輸出:
[2020-03-07T23:45:02.399-08:00, 2020-03-08T01:03:05.079-08:00] [2020-05-24T18:51:10.018-07:00, 2020-05-24T19:32:34.461-07:00, 2020-05-24T20:01:11.442-07:00]
宣告intervalLengtha的優點TemporalAmount是您可以自由地為其分配基于Duration時間的Period.
TemporalAmount intervalLength = Period.ofMonths(3);
在這種情況下,結果只是一組:
[2020-03-07T23:45:02.399-08:00, 2020-03-08T01:03:05.079-08:00, 2020-05-24T18:51:10.018-07:00, 509-320T :34.461-07:00, 2020-05-24T20:01:11.442-07:00]
關聯
Oracle 教程:解釋如何使用 java.time 的日期時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/350102.html
上一篇:分組依據比選擇的欄位少
