![](/img/trans.png)
[英]Group By two different keys in two different DataFrames using Spark Scala without join
[英]Join two dataframes with different records and size in Spark
似乎這個問題被問了幾次,但在以前的問題中提出的解決方案對我不起作用。
我有兩個不同尺寸的數據框,如下圖所示。 second
表first
是表一的一部分,但經過一些處理后,我又添加了一列column4
。 現在,我想加入這兩個表,這樣我有三個表Required
加盟后。
嘗試過的東西。
所以我做了幾個不同的解決方案,但沒有一個適合我。
我試過
val required =first.join(second, first("PDE_HDR_CMS_RCD_NUM") === second("PDE_HDR_CMS_RCD_NUM") , "left_outer")
我也試過
val required = first.withColumn("SEQ", when(second.col("PDE_HDR_FILE_ID") === (first.col("PDE_HDR_FILE_ID").alias("PDE_HDR_FILE_ID1")), second.col("uniqueID")).otherwise(lit(0)))
在第二次嘗試中,我在收到錯誤.alias
后使用了.alias
提取過程中發生錯誤。 錯誤:org.apache.spark.sql.AnalysisException:已解析的屬性(s)uniqueID#775L 缺失。
感謝您花時間閱讀我的問題
要生成所需的結果,您應該在第一個表中的行標識列上連接兩個表。 假設c1 + c2 + c3
唯一標識第一個表中的每一行,以下是使用部分樣本數據集的示例:
import org.apache.spark.sql.functions._
import spark.implicits._
val df1 = Seq(
(1, "e", "o"),
(4, "d", "t"),
(3, "f", "e"),
(2, "r", "r"),
(6, "y", "f"),
(5, "t", "g"),
(1, "g", "h"),
(4, "f", "j"),
(6, "d", "k"),
(7, "s", "o")
).toDF("c1", "c2", "c3")
val df2 = Seq(
(3, "f", "e", 444),
(5, "t", "g", 555),
(7, "s", "o", 666)
).toDF("c1", "c2", "c3", "c4")
df1.join(df2, Seq("c1", "c2", "c3"), "left_outer").show
// +---+---+---+----+
// | c1| c2| c3| c4|
// +---+---+---+----+
// | 1| e| o|null|
// | 4| d| t|null|
// | 3| f| e| 444|
// | 2| r| r|null|
// | 6| y| f|null|
// | 5| t| g| 555|
// | 1| g| h|null|
// | 4| f| j|null|
// | 6| d| k|null|
// | 7| s| o| 666|
// +---+---+---+----+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.