简体   繁体   English

如何使用一些类似的值和多个键/ scala连接数据帧

[英]how to join dataframes with some similar values and multiple keys / scala

I have problems to get following table. 得到下表我有问题。 The first two tables are my source tables which i would like to join. 前两个表是我想要加入的源表。 the third table is how i would like to have it. 第三个表是我想要的。

I tried it with an outer join and used the keys "ID" and "date" but the result is not the same like in this example. 我尝试使用外连接并使用键“ID”和“日期”,但结果与此示例中的结果不同。 The problem is, that some def_ values in each table have the same date and i would like to get them in the same row. 问题是,每个表中的一些def_值具有相同的日期,我想将它们放在同一行中。

I used following join: 我使用以下加入:

val df_result = df_1.join(df_2, Seq("ID", "date"), "outer")

df
+----+-----+-----------+
|ID  |def_a| date      |
+----+-----+-----------+
|  01|    1| 2019-01-31|
|  02|    1| 2019-12-31| 
|  03|    1| 2019-11-30|
|  01|    1| 2019-10-31|

df
+----+-----+-----+-----------+
|ID  |def_b|def_c|date       |
+----+-----+-----+-----------+
|  01|    1|    0| 2017-01-31| 
|  02|    1|    1| 2019-12-31| 
|  03|    1|    1| 2018-11-30| 
|  03|    0|    1| 2019-11-30| 
|  01|    1|    1| 2018-09-30|
|  02|    1|    1| 2018-08-31|
|  01|    1|    1| 2018-07-31|

result
+----+-----+-----+-----+-----------+
|ID  |def_a|def_b|deb_c|date       |
+----+-----+-----+-----+-----------+
|  01|    1|    0|    0| 2019-01-31| 
|  02|    1|    1|    1| 2019-12-31| 
|  03|    1|    0|    1| 2019-11-30| 
|  01|    1|    0|    0| 2019-10-31| 
|  01|    0|    1|    0| 2017-01-31| 
|  03|    0|    1|    1| 2018-11-30| 
|  01|    0|    1|    1| 2018-09-30| 
|  02|    0|    1|    1| 2018-08-31|
|  01|    0|    1|    1| 2018-07-31|

I would be grateful for any help. 我将不胜感激任何帮助。

Hope the following code would be helpful — 希望以下代码有用 -

df_result
    .groupBy("ID", "date")
    .agg(
        max("a"),
        max("b"),
        max("c")
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM