[英]Grouping sets of data in Oracle SQL
我一直試圖將存儲在我的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
主要思想是在子查詢中隔離連續的項目序列( grp
列的計算)。 一旦你有了grp
專欄,其余的都很簡單。
select DENSE_RANK() over(partition by SUBSTR("location",1,1) ORDER BY SUBSTR("location",1,2))
as Rownumber,
"location" from Table1;
演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.