计算HIVE的中位数值

时间:2015-09-25 14:55:32

标签: statistics hive hiveql median percentile

我有下表t1:

key  value
 1   38.76
 1   41.19
 1   42.22
 2   29.35182
 2   28.32192
 3   33.66
 3   33.47
 3   33.35
 3   33.47
 3   33.11
 3   32.98
 3   32.5

我想计算每个关键组的中位数。根据{{​​3}},percentile_approx函数应该适用于此。每组的中位数值为:

1  41.19
2  28.83
3  33.35

但是,percentile_approx函数会返回以下内容:

1  39.974999999999994
2  28.32192
3  33.23.0000000000004

这显然不是中值。

这是我跑的查询:

select key, percentile_approx(value, 0.5, 10000) as median
from t1
group by key

似乎没有考虑每组一个值,导致错误的中位数。订购不会影响结果。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在Hive中,无法使用可用的内置函数直接计算中位数。下面的查询用于查找中位数。

    set hive.exec.parallel=true;
    select temp1.key,temp2.value
    from 
      (
      select key,cast(sum(rank)/count(key) as int) as final_rank
      from
        (
        select key,value,
        row_number() over (partition by key order by value) as rank
        from t1
      ) temp
      group by key )temp1
    inner join
    ( select key,value,row_number() over (partition by key order by value) as rank
      from t1  )temp2
       on 
       temp1.key=temp2.key and
       temp1.final_rank=temp3.rank;

上面的查询通过排序键的值来查找每个键的row_number。最后,它将采用每个键的中间row_number来给出中值。此外,我还添加了一个参数“hive.exec.parallel = true;”,它可以并行运行独立任务。