【问题标题】:How to group time column into 5 second intervals and count rows using Presto?如何使用 Presto 将时间列分组为 5 秒间隔并计算行数?
【发布时间】:2018-04-14 10:18:50
【问题描述】:

我正在使用 Presto 和 Zeppelin。有很多原始数据。 我必须总结这些数据。

我想每 5 秒分组一次。

serviceType        logType     date
------------------------------------------------------
service1           log1        2017-10-24 23:00:23.206
service1           log1        2017-10-24 23:00:23.207
service1           log1        2017-10-24 23:00:25.206
service2           log1        2017-10-24 23:00:24.206
service1           log2        2017-10-24 23:00:27.206
service1           log2        2017-10-24 23:00:29.302

然后是结果

serviceType        logType     date                       cnt
--------------------------------------------------------------
service1           log1        2017-10-24 23:00:20          2
service2           log1        2017-10-24 23:00:20          1
service1           log1        2017-10-24 23:00:25          1
service1           log2        2017-10-24 23:00:25          2

首先,我必须将存储的数据迁移到新表。

其次,我必须对数据进行分组并实时保存到新表中。

sql脚本很难写。

请帮帮我。

我必须使用 python 解释器吗?

【问题讨论】:

    标签: sql apache-zeppelin presto


    【解决方案1】:

    你可以

    1. date_trunc 丢弃timestamp 的毫秒部分
    2. 您可以使用 ts - interval '1' second * (second(ts) % 5) 将不带毫秒部分的 timestamp 舍入到 5 秒

    将这些放在一起的示例:

    presto> SELECT ts_rounded, count(*)
         -> FROM (
         ->     SELECT date_trunc('second', ts) - interval '1' second * (second(ts) % 5) AS ts_rounded
         ->     FROM (VALUES timestamp '2017-10-24 23:01:20.206',
         ->         timestamp '2017-10-24 23:01:23.206',
         ->         timestamp '2017-10-24 23:01:23.207',
         ->         timestamp '2017-10-24 23:01:26.206') AS t(ts)
         -> )
         -> GROUP BY ts_rounded ORDER BY ts_rounded;
           ts_rounded        | _col1
    -------------------------+-------
     2017-10-24 23:01:20.000 |     3
     2017-10-24 23:01:25.000 |     1
    (2 rows)
    

    【讨论】:

      【解决方案2】:

      这给出了 5 分钟的桶

      from_unixtime((cast(to_unixtime(timestamp_column_name) as bigint)/60/5)*60*5)
      

      这给出了 60 秒的存储桶

      from_unixtime((cast(to_unixtime(timestamp_column_name) as bigint)/60)*60)
      

      这给出了 5 秒的桶

      from_unixtime((cast(to_unixtime(timestamp_column_name) as bigint)/5)*5)
      

      这是迄今为止我所知道的最好的技巧,因为它超级简单并且适用于所有数据库。它在舍入时使用精度损失。我们所有的时间戳都以 UTC 毫秒为单位,因此通过窗口进行聚合非常容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 2019-09-07
        • 2021-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多