【问题标题】:Hive summary function inside case statement案例语句中的 Hive 汇总功能
【发布时间】:2017-01-17 10:51:22
【问题描述】:

我正在尝试编写一个简单的 Hive 查询:

select sum(case when pot_sls_q > 2* avg(pit_sls_q) then 1 else 0)/count(*) from prd_inv_fnd.item_pot_sls where dept_i=43 and class_i=3 where p_wk_end_d = 2014-06-28;

这里pit_sls_qpot_sls_q 都是Hive 表中的列,我想要pot_sls_q 的记录比例超过pit_sls_q 平均值的2 倍。但是我得到错误:

FAILED: SemanticException [Error 10128]: Line 1:95 Not yet supported place for UDAF 'avg'

为了鬼混,我什至尝试使用一些窗口函数:

select sum(case when pot_sls_q > 2* avg(pit_sls_q) over (partition by dept_i,class_i)  then 1 else 0 end)/count(*) from prd_inv_fnd.item_pot_sls where dept_i=43 and class_i=3 and p_wk_end_d = '2014-06-28';

考虑到在相同条件下过滤或分区数据本质上是“相同”数据这一事实很好,但即使这样我也会出错:

FAILED: SemanticException [Error 10002]: Line 1:36 Invalid column reference 'avg': (可能的列名是:p_wk_end_d、dept_i、class_i、item_i、pit_sls_q、pot_sls_q)

请提出正确的做法。

【问题讨论】:

    标签: sql hadoop hive


    【解决方案1】:

    您在SUM 中使用AVG,这将不起作用(以及其他语法错误)。

    尝试解析AVG OVER ()这个:

    select sum(case when pot_sls_q > 2 * avg_pit_sls_q then 1 else 0 end) / count(*)
    from (
        select t.*,
            avg(pit_sls_q) over () avg_pit_sls_q
        from prd_inv_fnd.item_pot_sls t
        where dept_i = 43
            and class_i = 3
            and p_wk_end_d = '2014-06-28'
        ) t;
    

    【讨论】: