合并大量的列
Coalesce on huge number of columns
我正在 Hive 中开发一个 table,其中包含数十亿行和一百多列。
我需要合并 100 列中的第一个非零值。我能够做到这一点,但它涉及多行代码(每列一行)。我还必须创建另一列以相反的方式执行相同操作以找到最后一个非零值,这意味着至少还有 100。每列具有相同的命名约定,因此 balance0、balance1、balance2 等
我想知道是否有更好的方法用更少的代码行来做到这一点?我在网上搜索过,可以找到很多关于合并值的信息,但我似乎找不到任何有助于减少为此所需的代码行的内容。
我使用的代码的简化版本如下:
SELECT urn
,COALESCE( IF( balance0 <> '0', balance0, NULL )
,IF( balance1 <> '0', balance1, NULL )
,IF( balance2 <> '0', balance2, NULL )
,IF( balance3 <> '0', balance3, NULL )
,IF( balance4 <> '0', balance4, NULL )
,IF( balance5 <> '0', balance5, NULL )
,IF( balance6 <> '0', balance6, NULL )
,IF( balance7 <> '0', balance7, NULL )
,IF( balance8 <> '0', balance8, NULL )
,IF( balance9 <> '0', balance9, NULL )
,IF( balance10 <> '0', balance10, NULL )
,IF( balance11 <> '0', balance11, NULL )
,IF( balance12 <> '0', balance12, NULL )
,IF( balance13 <> '0', balance13, NULL )
,IF( balance14 <> '0', balance14, NULL )
,IF( balance15 <> '0', balance15, NULL )
,IF( balance16 <> '0', balance16, NULL )
,IF( balance17 <> '0', balance17, NULL )
,IF( balance18 <> '0', balance18, NULL )
,IF( balance19 <> '0', balance19, NULL )
,IF( balance20 <> '0', balance20, NULL )
,IF( balanceX.... etc to balance100
)
AS first_positive_balance
FROM table_x;
非常感谢您的帮助!
对于你在问题中描述的情况,我没有看到很多捷径..
您可以编写可以使用任意数量参数的自定义 UDF (genericUDF),但在调用 UDF 时仍然必须指定所有列。
对于评论中的案例(合并结构的许多元素),您可以编写一个自定义 UDF,它只接收结构作为参数。 hive 结构实际上表示为 Object[],因此无论有多少结构元素,都可以很容易地在结构元素上实现任何功能。
Here's an example 接收结构列表作为参数的通用 UDF。
我正在 Hive 中开发一个 table,其中包含数十亿行和一百多列。
我需要合并 100 列中的第一个非零值。我能够做到这一点,但它涉及多行代码(每列一行)。我还必须创建另一列以相反的方式执行相同操作以找到最后一个非零值,这意味着至少还有 100。每列具有相同的命名约定,因此 balance0、balance1、balance2 等
我想知道是否有更好的方法用更少的代码行来做到这一点?我在网上搜索过,可以找到很多关于合并值的信息,但我似乎找不到任何有助于减少为此所需的代码行的内容。
我使用的代码的简化版本如下:
SELECT urn
,COALESCE( IF( balance0 <> '0', balance0, NULL )
,IF( balance1 <> '0', balance1, NULL )
,IF( balance2 <> '0', balance2, NULL )
,IF( balance3 <> '0', balance3, NULL )
,IF( balance4 <> '0', balance4, NULL )
,IF( balance5 <> '0', balance5, NULL )
,IF( balance6 <> '0', balance6, NULL )
,IF( balance7 <> '0', balance7, NULL )
,IF( balance8 <> '0', balance8, NULL )
,IF( balance9 <> '0', balance9, NULL )
,IF( balance10 <> '0', balance10, NULL )
,IF( balance11 <> '0', balance11, NULL )
,IF( balance12 <> '0', balance12, NULL )
,IF( balance13 <> '0', balance13, NULL )
,IF( balance14 <> '0', balance14, NULL )
,IF( balance15 <> '0', balance15, NULL )
,IF( balance16 <> '0', balance16, NULL )
,IF( balance17 <> '0', balance17, NULL )
,IF( balance18 <> '0', balance18, NULL )
,IF( balance19 <> '0', balance19, NULL )
,IF( balance20 <> '0', balance20, NULL )
,IF( balanceX.... etc to balance100
)
AS first_positive_balance
FROM table_x;
非常感谢您的帮助!
对于你在问题中描述的情况,我没有看到很多捷径.. 您可以编写可以使用任意数量参数的自定义 UDF (genericUDF),但在调用 UDF 时仍然必须指定所有列。
对于评论中的案例(合并结构的许多元素),您可以编写一个自定义 UDF,它只接收结构作为参数。 hive 结构实际上表示为 Object[],因此无论有多少结构元素,都可以很容易地在结构元素上实现任何功能。
Here's an example 接收结构列表作为参数的通用 UDF。