【问题标题】:Average count of elements in a set in hive?蜂巢中一组元素的平均数量?
【发布时间】:2016-08-16 11:27:36
【问题描述】:

我有两列 id 和 segment。段是逗号分隔的字符串集。我需要在所有表格中找到平均段数。一种方法是使用两个单独的查询 -

A - select count(*) from table_name;
B - select count(*) from table_name LATERAL VIEW explode(split(segment, ',') lTable AS singleSegment where segment != ""
avg = B/A

在上述情况下,答案是 8/4 = 2。

有没有更好的方法来实现这一点?

【问题讨论】:

    标签: hive aggregate-functions explode hiveql apache-hive


    【解决方案1】:

    试试:

    select sum(CASE segment 
               WHEN '' THEN 0 
               ELSE  size(split(segment,','))
               END
               )*1.0/count(*) from table_name;
    

    如果您的 id 字段是唯一的,并且您想向分段部分添加过滤器,或防止其他格式错误的 segment 值(例如 a,b,a,,b),您可以这样做:

    SELECT SUM(seg_size)*1.0/count(*) FROM (
        SELECT count(*) as seg_size from table_name
        LATERAL VIEW explode(split(segment, ',')) lTable AS singleSegment
        WHERE trim(singleSegment) != ""
        GROUP BY id
    ) sizes
    

    然后你可以在 where 子句中添加其他东西。

    但与更简单的查询相比,此查询需要两个 Hive 作业来运行,并且要求 id 字段是唯一的。

    【讨论】:

    • 上述查询的较长版本运行良好。谢谢!!
    • 是的,我删除了错误的第一个查询,所以你的意思是更短的查询,现在 :) @BlitzKrieg 更长的查询会更慢,但它确实提供了更多的灵活性。
    猜你喜欢
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2022-01-11
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2013-12-29
    相关资源
    最近更新 更多