【问题标题】:Presto SQL window aggregate looking back x hours/minutes/secondsPresto SQL 窗口聚合回顾 x 小时/分钟/秒
【发布时间】:2019-01-17 20:09:35
【问题描述】:

我想通过回顾 x 小时/分钟/秒前在 presto sql 上进行聚合。

数据

id    |       timestamp       |    status
-------------------------------------------
A     |   2018-01-01 03:00:00 |     GOOD
A     |   2018-01-01 04:00:00 |     BAD
A     |   2018-01-01 05:00:00 |     GOOD
A     |   2018-01-01 09:00:00 |     BAD
A     |   2018-01-01 09:15:00 |     BAD
A     |   2018-01-01 13:00:00 |     GOOD
A     |   2018-01-01 14:00:00 |     GOOD
B     |   2018-02-01 09:00:00 |     GOOD
B     |   2018-02-01 10:00:00 |     BAD

结果:

id    |       timestamp       |    status    | bad_status_count
----------------------------------------------------------------
A     |   2018-01-01 03:00:00 |     GOOD     |       0 
A     |   2018-01-01 04:00:00 |     BAD      |       1
A     |   2018-01-01 05:00:00 |     GOOD     |       1
A     |   2018-01-01 09:00:00 |     BAD      |       1
A     |   2018-01-01 09:15:00 |     BAD      |       2
A     |   2018-01-01 13:00:00 |     GOOD     |       0 
A     |   2018-01-01 14:00:00 |     GOOD     |       0
B     |   2018-02-01 09:00:00 |     GOOD     |       0
B     |   2018-02-01 10:00:00 |     BAD      |       1

我按业务计算过去 3 小时内的不良状态。我怎样才能做到这一点? 我正在尝试这样的事情:

SELECT
  id,
  timestamp,
  status
  count(status) over(partition by id order by timestamp range between interval '3' hour and current_row) as bad_status_count
from table

当然它还不起作用,我仍然必须过滤掉不良状态。我收到了这个错误: Error running query: line 7:1: Window frame start value type must be INTEGER or BIGINT(actual interval day to second)

【问题讨论】:

    标签: sql window presto


    【解决方案1】:

    我不是 100% 如何在 PrestoDB 中表达这一点,但关键思想是将时间戳转换为小时:

    select t.*,
           sum(case when status = 'Bad' then 1 else 0 end) over
               (partition by id
                order by hours
                range between -3 and current row
               ) as bad_status
    from (select t.*,
                 date_diff(hour, '2000-01-01', timestamp) as hours
          from t
         ) t;
    

    【讨论】:

    • 而我们想将时间段缩短为分秒,我们只需分别输入date_diff(minute, '2000-01-01', timestamp)date_diff(second, '2000-01-01', timestamp)即可。
    • @addicted 。 . .如果这适用于几个小时,那么更改时间段将适用于其他时间单位。
    • date_diff 有效,但 -3 和当前行之间的范围对我不起作用。有一个错误(`不匹配的输入'row'。期望:'%'、'*'、'+'、'-'、'.'、'/'、'AT'、'['、'||' , )。似乎这不是预期的输入
    • @addicted 。 . .将 current row 更改为 0 following,就像您最初拥有的那样。 range 窗口规范可能需要这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多