Hive 按组计算中位数和平均值

Hive compute median and average by groups

我有一个按州和县统计的数据集,我想按州和县计算中位数和平均值,例如:

有:

ID  state    county  count
1   MD       aa          2
2   MD       aa          4
3    VA        bb         1
4    VA        bb         2
5    VA        bb         4
6    VA        cc          7
7    VA        cc          8

想要:

到目前为止,我遇到的错误是:

Select id,  STATE,COUNTY,count,
percentile(cast(count as BIGINT), 0.5) OVER() as overall_median, 
round(avg(count),2) OVER() as overall_avg,

percentile(cast(count as bigint),0.5) OVER(PARTITION BY id,STATE) as med_state,
percentile(cast(count as bigint),0.5) as med_county,

AVG(count) OVER (PARTITION BY id, STATE) as avg_state,
AVG(count) AS avg_county,
from have
group by id, state, county

不使用组时收到错误:

ERROR: Execute error: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: SemanticException Failed to breakup Windowing invocations into Groups. At least 1 group must only depend on input columns. Also check for circular dependencies.Underlying error: org.apache.hadoop.hive.ql.parse.SemanticException: Line 1:457 Expression not in GROUP BY key 'id'

没有分组的代码:

Select id,  STATE,county,count,
percentile(cast(count as BIGINT), 0.5) OVER() as overall_median, 
round(avg(count),2) OVER() as overall_avg,

percentile(cast(count as bigint),0.5) OVER(PARTITION BY id,STATE) as med_state,
percentile(cast(count as bigint),0.5) OVER(PARTITION BY id,STATE,county) as med_county,


AVG(count) OVER (PARTITION BY id, STATE) as avg_state,
AVG(count) OVER (PARTITION BY id, STATE, county) as avg_county,
from have

谢谢!

修复:回合(平均(计数)OVER(),2)

    select 
        id, STATE, county, count,
        percentile(cast(count as BIGINT), 0.5) OVER() as overall_median, 
        round(avg(count) OVER(), 2) as overall_avg,

        percentile(cast(count as bigint), 0.5) OVER(PARTITION BY id, STATE) as med_state,
        percentile(cast(count as bigint), 0.5) OVER(PARTITION BY id, STATE, county) as med_county,

        AVG(count) OVER (PARTITION BY id, STATE) as avg_state,
        AVG(count) OVER (PARTITION BY id, STATE, county) as avg_county
    from 
        have

提示:不要使用关键字(即计数)作为列名 - 将来会遇到很多问题