【发布时间】:2019-06-23 05:41:25
【问题描述】:
我必须每三个月回顾一次,并使用 with 列添加上个月的金额。
val data = Seq(("1","201706","5"),("1","201707","10"),("2","201604","12"),("2","201601","15")).toDF("id","yyyyMM","amount")
+---+------+------+
| id|yyyyMM|amount|
+---+------+------+
| 1|201706| 5|
| 1|201707| 10|
| 2|201604| 12|
| 2|201601| 15|
+---+------+------+
所需的输出应如下所示。对于每个月我们必须回顾三个月,我可以通过使用火花窗口滞后功能来做到这一点。我们应该如何包含添加附加记录的功能
+---+---------+------+-----------+-------+-----------+-------+
| id|yearmonth|amount|yearmonth-1|amount2|yearmonth-2|amount3|
+---+---------+------+-----------+-------+-----------+-------+
| 1| 201709| 0| 201708| 0| 201707| 10|
| 1| 201708| 0| 201707| 10| 201706| 5|
| 1| 201707| 10| 201706| 5| 201705| 0|
| 1| 201706| 5| 201705| 0| 201706| 0|
| 2| 201606| 0| 201605| 0| 201604| 12|
| 2| 201605| 0| 201604| 12| 201603| 0|
| 2| 201604| 12| 201603| 0| 201602| 0|
| 2| 201603| 0| 201602| 0| 201601| 15|
| 2| 201602| 0| 201601| 15| 201512| 0|
| 2| 201601| 15| 201512| 0| 201511| 0|
+---+---------+------+-----------+-------+-----------+-------+
我的意思是表中的第一条记录就像期待。就像增加几个月一样。采取以下记录。
+---+---------+------+-----------+-------+-----------+-------+
| id|yearmonth|amount|yearmonth-1|amount2|yearmonth-2|amount3|
+---+---------+------+-----------+-------+-----------+-------+
| 1| 201709| 0| 201708| 0| 201707| 10|
| 1| 201708| 0| 201707| 10| 201706| 5|
【问题讨论】:
标签: sql apache-spark apache-spark-sql window-functions