【问题标题】:Implementing SQL logic via Dataframes using Spark and Scala使用 Spark 和 Scala 通过 Dataframes 实现 SQL 逻辑
【发布时间】:2018-02-22 09:32:51
【问题描述】:

我在 Hive 表 t1 中有三列(c1、c2、c3)。我有检查特定列是否为空的 MySQL 代码。我有来自同一张表的数据框。我想通过具有三列 c1、c2、c3 的数据帧 df 实现相同的逻辑。

这里是 SQL-

if(
t1.c1=0 Or IsNull(t1.c1),
if(
IsNull(t1.c2/t1.c3),
1,
t1.c2/t1.c3
),
t1.c1
) AS myalias

我在 scala 中使用“when”作为 SQL 的“if”的替代方案起草了以下逻辑。我在编写“或”逻辑时遇到问题(下面加粗)。如何使用 Scala 通过 Spark 数据框编写上述 SQL 逻辑?

val df_withalias = df.withColumn("myalias",when(
  Or((df("c1") == 0), isnull(df("c1"))),
  when(
    (isNull((df("c2") == 0)/df("c3")),
  )
)
)

上面的逻辑怎么写?

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    首先,您可以使用Column|| 运算符来构造逻辑或条件。另外 - 请注意,when 仅接受 2 个参数(条件和值),如果您想提供替代值(在不满足条件时使用) - 您需要使用 .otherwise

    val df_withalias = df.withColumn("myalias",
      when(df("c1") === 0 || isnull(df("c1")),
        when(isnull(df("c2")/df("c3")), 1).otherwise(df("c2")/df("c3"))
      ).otherwise(df("c1"))
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-22
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      相关资源
      最近更新 更多