【问题标题】:How to get min and max from 7 columns in Hive Hue excluding zeros如何从 Hive Hue 中的 7 列中获取最小值和最大值,不包括零
【发布时间】:2021-04-03 08:28:01
【问题描述】:

我有一个有 9 列的表。下面是它的结构

对于不包括零的行,我需要这些列的最小值和最大值。下面是需要的表结构

如果您看到 min 和 max 列,则 min 是特定行中除零之外的 7 列(col1 到 col7)的最小值,max 是该行 7 列(col1 到 col7)中的最大值。

请帮助我在 hive (hue) 中完成此操作。

【问题讨论】:

    标签: sql hive hiveql hue


    【解决方案1】:

    您可以使用leastgreatest 获取最小值和最大值,并使用when 删除0

    select *,
        least(
            case when col1 != 0 then col1 else 99999999 end,
            case when col2 != 0 then col2 else 99999999 end,
            case when col3 != 0 then col3 else 99999999 end,
            case when col4 != 0 then col4 else 99999999 end,
            case when col5 != 0 then col5 else 99999999 end,
            case when col6 != 0 then col6 else 99999999 end,
            case when col7 != 0 then col7 else 99999999 end,
        ) as `Min`
        greatest(
            case when col1 != 0 then col1 else -99999999 end,
            case when col2 != 0 then col2 else -99999999 end,
            case when col3 != 0 then col3 else -99999999 end,
            case when col4 != 0 then col4 else -99999999 end,
            case when col5 != 0 then col5 else -99999999 end,
            case when col6 != 0 then col6 else -99999999 end,
            case when col7 != 0 then col7 else -99999999 end
        ) as `Max`
    from mytable
    

    【讨论】:

    • 这不起作用,因为当一个或多个参数为 NULL 时,最小函数已固定为返回 NULL。例如,如果一列的值为零,则 case 语句将给出 NULL 作为输出,这使得最小或最大函数结果为 NULL。但 NULL 不是所需的输出。
    • 哦,我没有意识到 Hive 有这种行为。为least 添加else 99999999 和为greatest 添加else -99999999 怎么样?
    • 给出 99999999 是没有意义的,因为如果从 col1 到 col7 的样本值是 0,25,2,587,0,1,45,我们需要结果是 1 而不是 99999999。
    • @Pushpakkvh 不确定您是否理解我的评论,但请您看一下编辑后的答案吗?
    【解决方案2】:

    您可以使用明确的case 表达式:

    select (case when col1 <> 0 and col1 >= col2 and col1 >= col3 and col1 > =col4 and col1 >= col5 and col1 >= col6 and col1 >= col7
                 then col1
                 . . .
            end)
    

    这是很多打字。这可能表明您的数据存储不正确——您应该为每列设置单独的行。您可以通过扩展数据和重新聚合来模拟这一点:

    select name, state, col1, col2, col3, col4, col5, col6, col7,
           min(case when col1 <> 0 then col1 end) as min_value,
           max(case when col1 <> 0 then col1 end) as max_value,
    from ((select t.*, col1 as col from t) union all
          (select t.*, col2 as col from t) union all
          (select t.*, col3 as col from t) union all
          (select t.*, col4 as col from t) union all
          (select t.*, col5 as col from t) union all
          (select t.*, col6 as col from t) union all
          (select t.*, col7 as col from t)
         ) x
    group by name, state, col1, col2, col3, col4, col5, col6, col7;
          
    

    【讨论】:

    • 这可能会奏效,但这会大大增加处理时间,因为我们正在考虑相同的列并进行联合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2020-09-22
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多