在Spark Scala中,我试图创建一列,其中包含开始日期和结束日期之间(包括结束日期)的每月日期数组。
例如,如果我们有2018-02-07和2018-04-28,则数组应包含[2018-02-01、2018-03-01、2018-04-01]。
除了每月版本,我还要创建一个季度版本,即[2018-1,2018-2]。
示例输入数据:
id startDate endDate
1_1 2018-02-07 2018-04-28
1_2 2018-05-06 2018-05-31
2_1 2017-04-13 2017-04-14
预期(每月)输出1:
id startDate endDate dateRange
1_1 2018-02-07 2018-04-28 [2018-02-01, 2018-03-01, 2018-04-01]
1_1 2018-05-06 2018-05-31 [2018-05-01]
2_1 2017-04-13 2017-04-14 [2017-04-01]
最终预期(每月)输出2:
id Date
1_1 2018-02-01
1_1 2018-03-01
1_1 2018-04-01
1_2 2018-05-01
2_1 2017-04-01
我有spark 2.1.0.167,Scala 2.10.6和JavaHotSpot 1.8.0_172。
我已经尝试在此处实现对类似(日级)问题的几种答案,但是我正在努力使月度/季度版本能够正常工作。
下面从start和endDate创建一个数组并将其爆炸。但是,我需要展开一列,其中包含所有之间的每月(季度)日期。
val df1 = df.select($"id", $"startDate", $"endDate").
// This just creates an array of start and end Date
withColumn("start_end_array"), array($"startDate", $"endDate").
withColumn("start_end_array"), explode($"start_end_array"))
谢谢您的潜在客户。
case class MyData(id: String, startDate: String, endDate: String, list: List[String])
val inputData = Seq(("1_1", "2018-02-07", "2018-04-28"), ("1_2", "2018-05-06", "2018-05-31"), ("2_2", "2017-04-13", "2017-04-14"))
inputData.map(x => {
import java.time.temporal._
import java.time._
val startDate = LocalDate.parse(x._2)
val endDate = LocalDate.parse(x._3)
val diff = ChronoUnit.MONTHS.between(startDate, endDate)
var result = List[String]();
for (index <- 0 to diff.toInt) {
result = (startDate.getYear + "-" + (startDate.getMonth.getValue + index) + "-01") :: result
}
new MyData(x._1, x._2, x._3, result)
}).foreach(println)