如何在scala中同时编写select和case语句



我是scala的新手,我有一个下面的sql需要转换为scala,我已经粘贴了我尝试过的内容,但我遇到了一个错误。

SQL代码:

select (jess,
mark,
timestamp1,
timestamp2,
(CASE WHEN timestamp1>timstamp2 then null else salary) as salary,
(CASE WHEN timestamp1>timstamp2 then null else manager) as manager
)

我尝试过的Scala代码:

df.select (jess,
mark,
timestamp1,
timestamp2,
salary
)
.withColumn("salary", when($"timestamp1">$"timstamp2", salary ).otherwise("null"))

有不同的写法吗。

如上所述,有错误消息会更容易,但我现在可以看到的是:

  1. 您在"之后的选择中缺少逗号;标记";柱
  2. 在你的例子中,你第一次在没有"选择"的情况下进行选择;工资;列,但是您尝试在when/otherwise中使用此列。在第一次选择中包括薪资,或在选择前使用"列">

编辑:如果你想在内部选择案例,你可以这样做:

import org.apache.spark.sql.functions.{when, col}

df.select(col("jess"),
col("mark"),
col("timestamp1"),
col("timestamp2"),
when(col("timestamp1") > col("timestamp2"),salary)
.otherwise("null").alias("salary")
)

如果您想了解更多关于案例/时间的信息,请阅读以下内容:https://sparkbyexamples.com/spark/spark-case-when-otherwise-example/

最新更新