【问题标题】:Fetch the column which has the Max value for a row in Hive获取 Hive 中一行的最大值的列
【发布时间】:2017-02-08 13:20:34
【问题描述】:

我有一个场景,我需要从三列中选择行中的最大值,有一个名为 Greatest 的函数,但它在我的 Hive 0.13 版本中不起作用。

请提出更好的方法来完成它。

示例表:

+---------+------+------+------+
| Col1    | Col2 | Col3 | Col4 |
+---------+------+------+------+
| Group A | 1    | 2    | 3    |
+---------+------+------+------+
| Group B | 4    | 5    | 1    |
+---------+------+------+------+
| Group C | 4    | 2    | 1    |
+---------+------+------+------+

预期结果:

+---------+------------+------------+
| Col1    | output_max | max_column |
+---------+------------+------------+
| Group A | 3          | Col4       |
+---------+------------+------------+
| Group B | 5          | col3       |
+---------+------------+------------+
| Group C | 4          | col2       |
+---------+------------+------------+

【问题讨论】:

    标签: sql hadoop hive max hiveql


    【解决方案1】:
    select  col1
           ,tuple.col1                as output_max
           ,concat('Col',tuple.col2)  as max_column
    
    from   (select  Col1
                   ,sort_array(array(struct(Col2,2),struct(Col3,3),struct(Col4,4)))[2] as tuple
            from    t
            ) t
    ;
    

    sort_array(数组)
    根据数组元素的自然顺序对输入数组进行升序排序并返回 (从 0.9.0 版开始)。 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF


    hive> select  col1
        >        ,tuple.col1                as output_max
        >        ,concat('Col',tuple.col2)  as max_column
        >     
        > from   (select  Col1
        >                ,sort_array(array(struct(Col2,2),struct(Col3,3),struct(Col4,4)))[2] as tuple
        >         from    t
        >         ) t
        > ;
    OK
    Group A 3   Col4
    Group B 5   Col3
    Group C 4   Col2
    

    【讨论】:

    • Dudu,感谢您的帮助,也感谢您格式化问题中的表格。如果在上面的示例中 col2,3,4 是日期而不是整数,我有一个快速澄清的问题,如果元组将在一个场景中工作?请建议
    • 是的,它应该可以工作(hive 中的日期是 INO 格式 YYYY-MM-DD)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 2018-10-14
    • 2020-05-20
    • 2013-06-21
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多