2017-09-04 112 views
0

我有一個可以啓動或停止的服務。每個操作都會生成一個包含時間戳和操作類型的記錄。最終,我最終得到一系列時間戳記的操作記錄。現在我想計算一天中服務的正常運行時間。這個想法很簡單。對於每對啓動/停止記錄,計算時間跨度並進行總結。但是如果可能的話,我不知道如何使用Hive來實現它。我可以創建表來存儲中間結果。這是主要的阻塞問題,還有一些其他小問題。例如,一些開始/停止對可能跨越一天。任何想法如何處理這個小問題也將不勝感激。使用Hive腳本的每個開始/結束對的處理時間跨度

樣本數據:

Timestamp    Operation 
...      ... 
2017-09-03 23:59:00  Start 
2017-09-04 00:01:00  Stop 
2017-09-04 06:50:00  Start 
2017-09-04 07:00:00  Stop 
2017-09-05 08:00:00  Start 
...      ... 

服務正常運行時間爲2017-09-04應該然後是1 + 10 = 11分鐘。請注意,第一個時間間隔跨越09-0309-04,並且只計入落在09-04範圍內的部分。

+0

可以提供有關輸入/輸出的例子嗎? – hlagos

+0

以表格格式添加數據樣本(〜10行),包括所需結果。 –

+0

@DuduMarkovitz新增了一個例子,謝謝。 – Lingxi

回答

1
select  to_date(from_ts)             as dt 
      ,sum (to_unix_timestamp(to_ts) - to_unix_timestamp(from_ts))/60 as up_time_minutes 

from  (select  case when pe.i = 0      then from_ts else cast(date_add(to_date(from_ts),i) as timestamp) end as from_ts 
         ,case when pe.i = datediff(to_ts,from_ts) then to_ts else cast(date_add(to_date(from_ts),i+1) as timestamp) end as to_ts 

      from  (select `operation` 
           ,`Timestamp`          as from_ts 
           ,lead(`Timestamp`) over (order by `Timestamp`) as to_ts 

         from t 
         ) t 

         lateral view posexplode(split(space(datediff(to_ts,from_ts)),' ')) pe as i,x 

      where  `operation` = 'Start' 
        and to_ts is not null 
      ) t 

group by to_date(from_ts) 
; 

+------------+-----------------+ 
|  dt  | up_time_minutes | 
+------------+-----------------+ 
| 2017-09-03 | 1.0    | 
| 2017-09-04 | 11.0   | 
+------------+-----------------+ 
相關問題