sql - Scala 如何在使用 sqlContext 的查询中处理 isnull 或 ifnull

标签 sql scala apache-spark isnull

我有两个数据文件如下:

course.txt 
id,course 
1,Hadoop
2,Spark
3,HBase
5,Impala

Fee.txt 
id,amount 
2,3900
3,4200
4,2900

我需要列出所有类(class)信息及其费用:

sqlContext.sql("select c.id, c.course, f.amount from course c left outer join fee f on f.id = c.id").show
+---+------+------+
| id|course|amount|
+---+------+------+
|  1|Hadoop|  null|
|  2| Spark|3900.0|
|  3| HBase|4200.0|
|  5|Impala|  null|
+---+------+------+

如果类(class)未在费用表中显示,那么我不想显示空值,而是显示“N/A”。

我尝试了以下方法,但还没有得到它:

命令 1:

sqlContext.sql("select c.id, c.course, ifnull(f.amount, 'N/A') from course c left outer join fee f on f.id = c.id").show

错误:org.apache.spark.sql.AnalysisException:未定义函数 ifnull;第 1 行 40 号位

命令 2:

sqlContext.sql("select c.id, c.course, isnull(f.amount, 'N/A') from course c left outer join fee f on f.id = c.id").show

错误: org.apache.spark.sql.AnalysisException:Hive udf 类 org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNull 没有处理程序,因为:运算符“IS NULL”只接受 1 个参数......;第 1 行 40 号位

在 Scala 的 sqlContext 中处理这个问题的正确方法是什么?非常感谢。

最佳答案

使用 Spark DataFrame API,您可以使用 when/otherwiseisNull 条件:

val course = Seq(
  (1, "Hadoop"),
  (2, "Spark"),
  (3, "HBase"),
  (5, "Impala")
).toDF("id", "course")

val fee = Seq(
  (2, 3900),
  (3, 4200),
  (4, 2900)
).toDF("id", "amount")

course.join(fee, Seq("id"), "left_outer").
  withColumn("amount", when($"amount".isNull, "N/A").otherwise($"amount")).
  show
// +---+------+------+
// | id|course|amount|
// +---+------+------+
// |  1|Hadoop|   N/A|
// |  2| Spark|  3900|
// |  3| HBase|  4200|
// |  5|Impala|   N/A|
// +---+------+------+

如果您更喜欢使用 Spark SQL,这里有一个等效的 SQL:

course.createOrReplaceTempView("coursetable")
fee.createOrReplaceTempView("feetable")

val result = spark.sql("""
  select
    c.id, c.course,
    case when f.amount is null then 'N/A' else f.amount end as amount
  from
    coursetable c left outer join feetable f on f.id = c.id
""")

关于sql - Scala 如何在使用 sqlContext 的查询中处理 isnull 或 ifnull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205169/

相关文章:

sql - 如何获取habtm协会的arel表?

sql - Sequelize.js - 在 'findAll' 之后删除实例数组

regex - 带有可选前缀的正则表达式中的负后视

scala - Spark DataFrame - 使用 SQL 读取管道分隔文件?

apache-spark - DataFrameReader 在读取 avro 文件时抛出 "Unsupported type NULL"

mysql - 从连接表中仅选择具有 MAX(date) 的行中的所有列

sql - 在 WHERE 子句中多次使用同一列

scala - 具有多个索引的索引

scala - 在scala中添加一个对象列表

python - 为什么对 rand() 生成的列进行操作的 PySpark UDF 会失败?