2017-09-13 59 views
0

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

这里是SQL-

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

使用我起草了在阶以下逻辑“时”为“如果”到SQL的替代方案。我正在面对编写“或”逻辑的问题(下面粗体显示)。我如何使用Scala通过Spark数据框编写上述SQL逻辑?

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

我该如何编写上述逻辑?

回答

1

首先,您可以使用Column||算子来构造逻辑OR条件。此外 - 注意,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")) 
) 
+0

这工作!感谢Tzach。 –