gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:48:43 26 4
gpt4 key购买 nike

我有两个数据文件如下:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com