【问题标题】:how to apply max clause on column other than group by columns in Hive如何在 Hive 中除按列分组之外的列上应用 max 子句
【发布时间】:2019-09-27 03:32:57
【问题描述】:

我有一个包含如下数据的配置单元表。

Table
---------------------
c1     c2      c3
a      1       7
a      2       6
a      3       3
a      3       1
a      3       2

我想编写一个查询以从 c3 列中获取值 2。逻辑是,对于 c1 列,选择 max(c2),然后在该 max(c2) 中找到 max(c3)

我写了这样的查询

select c1, max(c3) from table1 
group by c1
having c2=max(c2)

但这不起作用,因为 Hive 说我只能使用作为 group by 一部分的有子句中的那些列。

请帮我解决这个问题。

注意:- 我需要一个查询。我可以在两个查询中写同样的内容

【问题讨论】:

  • 你想作为子查询吗?如果是,那么我有一个解决方案。
  • 我已经有了子查询的解决方案

标签: hive hiveql


【解决方案1】:
with your_data as (
select stack (5,
'a',1,7,
'a',2,6,
'a',3,3,
'a',3,1,
'a',3,2) as (c1,c2,c3)
)

select c1, max(c3) as max_c3
from
(
select c1,c2,c3,
       rank() over(partition by c1 order by c2 desc) rn --max(c2) marked 1
  from your_data
)s where rn=1 --filter records with max(c2)
group by c1

结果:

c1  max_c3  
a   3   

【讨论】:

  • 我们可以这样写rank() over(partition by c1,c2 order by c3 desc)
【解决方案2】:

使用聚合函数:

create table val
(alpha varchar(10),id1  int,id2 int);

insert into val values ('a',3,3);
insert into val values ('a',3,1);
insert into val values ('a',3,2);

select alpha,id2 from
(
select alpha,max(id1) as id1,max(id2) as id2
from val group by alpha
)agg

【讨论】:

  • 这对我不起作用,因为它根据我的数据和您使用的变量输出 id2=7。
猜你喜欢
  • 2020-09-08
  • 2022-01-09
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多