我一直在尝试将存储在我的 oracle 数据库中的数据中的组分开,以便进行更准确的分析。
Current Output
Time Location
10:00 A111
11:00 A112
12:00 S111
13:00 S234
17:00 A234
18:00 S747
19:00 A878
Desired Output
Time Location Group Number
10:00 A111 1
11:00 A112 1
12:00 S111 1
13:00 S234 1
17:00 A234 2
18:00 S747 2
19:00 A878 3
我一直在尝试使用 over 和 partition by 来分配值,但是我只能一直进行递增,而不仅仅是在更改时。也尝试使用滞后,但我努力利用它。
我只需要第二列中的值从 1 开始并在字段 1 的第一个字母更改时递增(使用 substr)。
这是我使用 row_number 的尝试,但我认为离得很远。输出中也会有一个时间列,上面也没有显示。
select event_time, st_location, Row_Number() over(partition by
SUBSTR(location,1,1) order
by event_time)
as groupnumber from pic
任何帮助将非常感激!
编辑:
Time Location Group Number
10:00 A-10112 1
11:00 A-10421 1
12:00 ST-10621 1
13:00 ST-23412 1
17:00 A-19112 2
18:00 ST-74712 2
19:00 A-87812 3
最佳答案
这是一个缺口和孤岛问题。使用以下代码:
select location,
dense_rank() over (partition by SUBSTR(location,1,1) order by grp)
from
(
select (row_number() over (order by time)) -
(row_number() over (partition by SUBSTR(location,1,1) order by time)) grp,
location,
time
from data
) t
order by time
dbfiddle demo
主要思想是在子查询中隔离连续的项目序列(计算
grp
列)。一旦您拥有 grp
,剩下的就很简单了。柱子。
关于sql - 在 Oracle SQL 中对数据集进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49772764/