【问题标题】:hive Expression Not In Group By Key (group by - having)hive Expression Not In Group By Key (group by - having)
【发布时间】:2021-05-31 10:49:19
【问题描述】:

我需要执行此查询来创建每个州和行业的平均增长率表

create table industry_growth as select state,sub_industry, avg(growth_percent)ind_growth from company_growth group by state, sub_industry having count(sub_industry>2);

我正在阅读这张桌子

state                   string                                      
sub_industry            string                                      
companyname             string                                      
growth_percent          double     

但我不断收到此错误

失败:SemanticException [错误 10025]:第 1:45 行表达式不在 GROUP BY 键'sub_industry'

帮助!

【问题讨论】:

  • 如果 sub_industry 在组中,那么这不能工作:有 count(sub_industry>2)。你想达到什么目的?请说明任务
  • 我正在努力争取各州发展最快的行业
  • 我认为括号是问题所在。你能试试这个create table industry_growth as select state,sub_industry, avg(growth_percent)ind_growth from company_growth group by state, sub_industry having count(sub_industry)>2; - 请注意我把> 2放在计数之外。不过我不确定你的逻辑。
  • 请提供一些有代表性的数据示例和预期结果
  • count(sub_industry>2) 应该做什么?你需要两个最好的 - 增长的 pwr 状态还是什么?

标签: sql hive hiveql top-n


【解决方案1】:

如果您需要每个州的前 n 个子行业,请计算 dense_rank 并过滤您想要每个州有多少个顶级行业。此查询将打印每个州的前 2 个子行业。如果每个州只需要 1 个顶级子行业,请将 where 子句中的过滤器更改为 where rnk = 1。如果两个行业具有相同的 ind_growth,它们将获得相同的排名,您将获得两行而不是一行。 row_number() 而不是 dense_rank() 将 1 分配给仅一条记录。

create table industry_growth as 

select state, sub_industry, ind_growth
from
(
select state, sub_industry, ind_growth , 
       dense_rank() over(partition by state, order by ind_growth desc) rnk
from
  (
   select state, sub_industry, avg(growth_percent) ind_growth 
     from company_growth group by state, sub_industry
  ) s 
) s where rnk <= 2 --for two most performing sub-industries per state
                   --rnk=1 is the most performing sub-industry per state

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    相关资源
    最近更新 更多