【问题标题】:Hive (Finding min of n columns in a row)Hive(连续查找 n 列中的最小值)
【发布时间】:2017-05-02 02:52:28
【问题描述】:

我在 Hive 中有一个包含 5 列的表,即电子邮件、a_first_date、b_first_date、c_first_date、d_first_date。

a、b、c、d 是用户可以执行的 4 种不同操作,上表中的 4 列表示用户执行第一个相应操作的日期。例如,'a_first_date' 中的值包含用户执行操作 a 的日期。

输出:我想要的是包含电子邮件的 2 列,overall_first_date 即用户第一次操作的日期?

示例表:(假设所有值都是BIGINT类型而不是电子邮件)

电子邮件,a_first_date,b_first_date,c_first_date,d_first_date
abc,20140707,20140702,20140801,20140907
xyz,20140107,20140822,20140201,20141007

输出:

email,overall_first_date
abc,20140702
xyz,20140107

可能的解决方案是编写一个 UDF 或使用 IF ELSE 将这些值相互比较,然后找到最小值,但这会涉及大量比较。

或者我可以做一个:

select email, min(action) as overall_first_date from

(
select email, a_first_date as action from mytable
UNION ALL
select email, b_first_date as action from mytable
UNION ALL
select email, c_first_date as action from mytable
UNION ALL
select email, d_first_date as action from mytable
) q1

GROUP BY email 

但这又不是一个好方法。

谁能提出一个更好的方法来实现这一点?

【问题讨论】:

标签: sql hadoop hive


【解决方案1】:

使用函数 least()。 例如; 选择 *, least(col1,col2,col3) 作为 minofcol 来自表名;

【讨论】:

    【解决方案2】:

    你可以使用 Hive 的数组函数:

    select email, 
           sort_array(array(a_first_date, b_first_date, c_first_date, d_first_date))[0]  as overall_first_date
    from table;
    

    我不确定这与 CASE 语句的性能相比如何。由于您没有很多列,因此两者都同样简单。

    【讨论】:

    • 这肯定比 CASE 简洁得多。太棒了!
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 2019-11-22
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 2013-01-24
      • 2020-10-15
      相关资源
      最近更新 更多