hive求一行的最大值

1. 准备数据表test2

create table test2(
a int,
b int,
c int,
d int,
e int);

 2. 准备2条数据

insert into table test2 values(5,1,3,8,6);
insert into table test2 values(6,2,5,11,9);

3. 现在要求出a,b,c,d,e 5个字段中每行的最大值和最小值。

  虽然hive中有min和max,但是那是求某列字段的最小值和最大值,在这里行不通。接下来使用hive中的数组排序方法来求解。

  思路: 先将字段合并到数组里面,然后使用数组排序函数。

select sort_array(array(a,b,c,d,e)) from test2;

 

这样,第一个就是最小值,最后一个就是最大值。完整代码如下:

select arr[0] as min_val, arr[4] as max_val 
from(
     select sort_array(array(a,b,c,d,e)) arr 
     from test2
)a;

  最终结果如下:

发布了348 篇原创文章 · 获赞 210 · 访问量 87万+

猜你喜欢

转载自blog.csdn.net/u010916338/article/details/102931536