hql滚动平均值

ckocjqey  于 2021-06-26  发布在  Hive
关注(0)|答案(1)|浏览(434)

这是我第一次在网上发帖子。所以我完全有可能违反了很多张贴规则。如果是这种情况,请让我知道,我将确保不会重复他们。
我一直在尝试在hive中的同一个查询中获得滚动平均数和绝对数,下面是我得到的结果。这在红移中非常有效,但在Hive中给了我一个错误。似乎不支持select语句中的子查询。想知道我是否可以得到一些关于如何修改这个查询以从配置单元中得到相同结果的指针。

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
oyjwcjzk

oyjwcjzk1#

您的示例中的技术称为相关子查询,并且往往非常慢。我建议使用带有range子句的窗口函数。
首先,在子查询中,计算每天的度量。然后在main中选择use window functions(使用窗口函数)来计算滚动总和/平均值。请参阅红移文档中的更多窗口函数示例。

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
;

相关问题