问题描述
我有两个数据框
-
来自一个数据帧的最大日期列:: 一列,第一行-df1,列:maxdate
-
具有日期列的多条记录:: df2列:col1,col2,col3..colDate
我要基于df1.maxdate过滤df2,df2.colDate > df1.maxdate
如果我像下面这样指定,那么它将起作用。
df2.filter(col("colDate").gt(lit(2020-01-01)))
但是,我无法使用df1.maxdate。 我正在尝试用Java实现这种解决方案。
两个dataFrame列中的数据类型均为日期
我正试图通过火花转换来实现这一目标
select * from a
where a.col > (select max(b.col) from b)
在我的例子中
Table a = df2
Table b = df1
解决方法
以下代码可能对您有帮助,
val df1 = Seq(('2020-01-02')).toDF("Maxate")
df1.show()
/*
+----------+
| Maxate|
+----------+
|2020-01-02|
+----------+
*/
val df2 = Seq(("2020-01-01","A","B"),("2020-01-03","C","D")).toDF("colDate","col1","col2")
/*
+----------+----+----+
| colDate|col1|col2|
+----------+----+----+
|2020-01-01| A| B|
|2020-01-03| C| D|
+----------+----+----+
*/
val maxDate=df1.collect.map(row=>row.getString(0)).mkString
df2.filter($"colDate">maxDate).show()
/*
+----------+----+----+
| colDate|col1|col2|
+----------+----+----+
|2020-01-03| C| D|
+----------+----+----+
*/
,
在createTempView
上 two dataframes
,然后使用 sql查询,我们可以过滤唯一需要的日期。
Example:
Option1: using createTempView:
df1.show()
//+----------+
//| Maxdate|
//+----------+
//|2020-01-01|
//+----------+
df2.show()
//+----------+----+----+
//| colDate|col1|col2|
//+----------+----+----+
//|2020-01-01| A| B|
//|2020-01-03| C| D|
//+----------+----+----+
df1.createOrReplaceTempView("tmp")
df2.createOrReplaceTempView("tmp1")
sql("select * from tmp1 where coldate > (select maxdate from tmp)").show()
//+----------+----+----+
//| colDate|col1|col2|
//+----------+----+----+
//|2020-01-03| C| D|
//+----------+----+----+
Option-2:Using dataframe variable:
另一种方法是存储到变量,然后使用该变量,然后在数据框 filter
中使用该变量。
val max_val=df1.collect()(0)(0).toString
df2.filter(col("colDate") > max_val).show()
//+----------+----+----+
//| colDate|col1|col2|
//+----------+----+----+
//|2020-01-03| C| D|
//+----------+----+----+
Option-3:Using dataframe crossJoin and expr:
在这种情况下,我们不是在创建变量,而是使用dataframe列仅过滤所需的行。
df2.crossJoin(df1).
filter(expr("colDate > Maxdate")).
drop("Maxdate").
show()
//+----------+----+----+
//| colDate|col1|col2|
//+----------+----+----+
//|2020-01-03| C| D|
//+----------+----+----+