spark/scala-从dataframe有条件地选择列

vc9ivgsu  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(472)

我有两张 hive 桌 A 以及 B 以及它们各自的Dataframe df_a 以及 df_b ```
A
+----+----- +-----------+
| id | name | mobile1 |
+----+----- +-----------+
| 1 | Matt | 123456798 |
+----+----- +-----------+
| 2 | John | 123456798 |
+----+----- +-----------+
| 3 | Lena | |
+----+----- +-----------+

B
+----+----- +-----------+
| id | name | mobile2 |
+----+----- +-----------+
| 3 | Lena | 123456798 |
+----+----- +-----------+

想做一个类似于

select A.name, nvl(nvl(A.mobile1, B.mobile2), 0) from A left outer join B on A.id = B.id

到目前为止我已经想出了

df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer").select(?)

我也不知道如何有条件地选择 `mobile1` 或者 `mobile2` 或者 `0` 就像我在Hive查询中做的那样。
有人能帮我吗?我用的是spark 1.5。
0dxa2lsx

0dxa2lsx1#

您可以使用sparksql的nanvl函数。使用后应类似于:

df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer")
.select(df_a("name"), nanvl(nanvl(df_a("mobile1"), df_b("mobile2")), 0))
hts6caw3

hts6caw32#

使用合并:

import org.apache.spark.sql.functions._
df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer").select(
     coalesce(df_a("mobile1"), df_b("mobile2"), lit(0))
)

如果存在,则使用mobile1;如果不存在,则使用mobile2;如果不存在mobile2,则使用0

相关问题