hive sql求多个字段的最小值和最大值的办法

 

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);

查询显示以下:spa

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

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

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

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

结果显示以下:排序

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

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;

 最终结果以下:class

相关文章
相关标签/搜索