【问题标题】:Rolling averages with HQL使用 HQL 的滚动平均值
【发布时间】:2018-11-20 20:41:59
【问题描述】:

这是我关于 SO 的第一篇文章。所以我完全有可能违反了很多发帖规则。如果是这种情况,请告诉我,我会确保不再重复。

我一直试图在 Hive 的同一查询中获得滚动平均值和绝对数,这就是我所拥有的。这在 Redshift 中运行良好,但在 Hive 中给了我一个错误。看起来不支持 select 语句中的子查询。想知道我是否可以获得一些关于如何修改此查询以从 Hive 中获得相同结果的指示。

select 
    a.ds,
    a.traffic_source,
    a.device_type,
    count(distinct a.unique_id) as daily_deduped_visits_human,
    (select
            count(distinct b.unique_id)
     from
            scratch.unique_human_id b
     where
            b.ds >= a.ds - 28
            and b.ds <= a.ds
            and a.traffic_source = b.traffic_source
            and a.device_type = b.device_type
    )/28 as rolling_28_day_average_visits_human
from
    scratch.unique_human_id a
group by 1,2,3    

【问题讨论】:

    标签: sql hive amazon-redshift rolling-computation


    【解决方案1】:

    您示例中的技术称为相关子查询,并且往往非常慢。我建议使用带有范围子句的窗口函数。

    首先,在子查询中,计算每天的指标。然后在主选择中使用窗口函数来计算滚动和/平均值。 See more window function examples in the Redshift docs.

    SELECT a.ds
         , a.traffic_source
         , a.device_type
         , a.daily_deduped_visits_human
         , SUM(a.daily_deduped_visits_human) 
           OVER (PARTITION BY a.traffic_source, a.device_type 
                 ORDER BY a.ds 
                 ROWS BETWEEN 28 PRECEDING AND CURRENT ROW 
                ) AS rolling_28_day_total_visits_human
         , AVG(a.daily_deduped_visits_human) 
           OVER (PARTITION BY a.traffic_source, a.device_type 
                 ORDER BY a.ds 
                 ROWS BETWEEN 28 PRECEDING AND CURRENT ROW 
                ) AS rolling_28_day_average_visits_human
    FROM (-- First calc the metric
          SELECT a.ds
               , a.traffic_source
               , a.device_type
               , COUNT(DISTINCT a.unique_id) AS daily_deduped_visits_human
          FROM scratch.unique_human_id a
          GROUP BY 1,2,3
          ) a
    GROUP BY 1,2,3,4
    ORDER BY a.traffic_source
         , a.device_type
         , a.ds
    ;
    

    【讨论】:

    • 非常感谢乔。虽然这不是我想要的,但你的解决方案(我必须说它比我最初发布的更优雅和更快(几秒钟对几分钟))确实给了我一个我要尝试的想法今天,看看结果如何。将我的发现与我的发现一起发布在这里。再次感谢!
    • 太棒了!很高兴它有帮助。
    猜你喜欢
    • 2021-06-04
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多