我有两个表,列table1有id,name 和table2只有id
table 1
--------------
id name
--------------
1 sudheer
2 sandeep
3 suresh
----------------
表2
--------
id
--------
1
2
-------
必填表应该是" id" table2不存在于table2中我的新列值应为" N"否则" Y"
table3
id name IND
1 sudheer Y
2 sandeep Y
3 suresh N
我已经尝试了以下步骤:
val df = hc.sql("select * from table1")
val df1 = hc.sql("select * from table2")
我试图在table2中再增加一个列(phone),因为我的join数据帧不包含table2中的id,基于我尝试将值设置为Y / N的空值
val df2 = df.join(df1,Seq("id"),"left_outer").withColumn("IND",exp(when(df1("phone")!= "null","Y").otherwise("N")))
但这并没有错误 found:布尔值 必需:org.apache.spark.sql.Column
有人可以建议如何在不向我的table2添加列的情况下获得所需的结果吗?
答案 0 :(得分:1)
您可以在table2
中使用默认值"Y"
和join
添加一个新列,并将null
值替换为"N"
val df1 = Seq(
(1, "sudheer"),
(2, "sandeep"),
(3, "suresh")
).toDF("id", "name")
val df2 = Seq(1, 2).toDF("id")
.withColumn("IND", lit("Y"))
val df3 = df1.join(df2, Seq("id"), "left_outer")
.na.fill("N")
或者您可以像使用when
一样使用
val df3 = df1.join(df2, Seq("id"), "left_outer")
.withColumn("IND", when($"IND".isNull, "N").otherwise("Y"))
希望这有帮助!