2017-09-04 23 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   | 
+------------+-----------------+ 
相关问题