0
我有一組天氣溫度數據,每5分鐘記錄一次記錄。我想彙總這15分鐘的數據。要做到這一點,我需要按日期,小時和分鐘對時間間隔進行分組,以便在以下分鐘間隔{5,10,15},{20,25,30},{35, 40,45},{50,55,60}。對於每組三個讀數,我應該取平均值。在Oracle SQL中按時間間隔聚合數據
我的數據有一個'DD-MMM-YY HH.MM'形式的時間戳,所以我提取了日期,小時和分鐘。我寫了一個案例來對時間戳進行分組,這並不是很正確,我不確定如何在平均函數中構建案例。
Select
Temperature,
Extract(Minute From Reading_Time) As Minutes,
Extract(Hour From Reading_Time) As Hours,
Cast(Reading_Time As Date) As Calendar_Date
From Weather_Data Where Weather_Station='BDX'
Case
When (Minutes>5 And Minutes<=15) Then
To_Timestamp(Calendar_Date &' '&'0'&Hours&':15', 'dd-mon-yy hh24:mi')
When (Minutes>20 And Minutes<=30) Then
To_Timestamp(Calendar_Date &' '&'0'&Hours&':30', 'dd-mon-yy hh24:mi')
When (Minutes>35 And Minutes<=45) Then
To_Timestamp(Calendar_Date &' '&'0'&Hours&':45', 'dd-mon-yy hh24:mi')
When (Minutes>50 And Minutes<=60) Then
To_Timestamp(Calendar_Date &' '&'0'&Hours&':60', 'dd-mon-yy hh24:mi')
End
修改後的代碼與戈登的反饋。我還重寫了案例邏輯以糾正時間上的輕微偏移。
select t.*,
(Case When Minutes <= 15 AND Minutes > 0
Then To_Timestamp(Calendar_Date &' '&Hours&':15', 'dd-mon-yy hh24:mi')
When Minutes <= 30 AND Minutes > 0
Then To_Timestamp(Calendar_Date &' '&Hours&':30', 'dd-mon-yy hh24:mi')
When Minutes <= 45 AND Minutes > 0
Then To_Timestamp(Calendar_Date &' '&Hours&':45', 'dd-mon-yy hh24:mi')
When Minutes = 0
Then To_Timestamp(Calendar_Date &' '&Hours&':00', 'dd-mon-yy hh24:mi')
Else To_Timestamp(Calendar_Date &' '&(Hours+1)&':00', 'dd-mon-yy hh24:mi')
End) As Aggregated_Timestamp
from (Select average(Temperature), Extract(Minute From Reading_Time) As Minutes,
Extract(Hour From Reading_Time) As Hours, Cast(Reading_Time As Date) As Calendar_Date
From Weather_Data
Where Weather_Station = 'BDX'
Group by Aggregated_Time
) t
這是非常有益的,戈登!我仍然在努力的唯一事情就是爲時間戳獲得一個獨特的條目,並對共享時間戳的三個溫度值進行平均。我修改了我在上面的代碼中嘗試的內容。 – user2242044
您需要按'case'語句的結果進行分組。根據SQL引擎的不同,您可以在'group by'子句中重複整個表達式,使用列的名稱或使用子查詢。 –