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;
最终结果如下:
来源: http://www.bubuko.com/infodetail-3035010.html