我目前正在尝试在pyspark中创建一个按四个元素排序的窗口分区。但是,这些元素之一需要进行限制,以使元素2、3、4的排序仅发生在无边界的排序元素1的当前行上。
+-----------+--------+--------+--------+---------------------------+
| Sort 1 | Sort 2 | Sort 3 | Sort 4 | Output: Days Between Sort |
+-----------+--------+--------+--------+---------------------------+
| 1/1/2012 | 0 | 0 | 1 | N/A |
+-----------+--------+--------+--------+---------------------------+
| 2/1/2012 | 0 | 0 | 2 | 1 |
+-----------+--------+--------+--------+---------------------------+
| 15/1/2012 | 0 | 0 | 3 | 13 |
+-----------+--------+--------+--------+---------------------------+
| 10/1/2012 | 0 | 1 | 0 | 8 |
+-----------+--------+--------+--------+---------------------------+
在上面的示例中,行之间的天数将通过获取日期(排序1),然后在排序1的当前行之前的无界之前按升序2,3,4进行排序来计算。这就是为什么10 /由于1/2012与2/1/2012相比而不是15/1/2012,因此介于8之间。
作为参考,需要对2,3,4进行排序,因为在示例表范围之外有一些示例需要进行这种排序。
以下是我想像的结果:如果可以包含两个Orderby语句,它将看起来像。
df = df.withColumn("lag_creation_date", F.lag("createdDate", 1).over(Window.partitionBy("X").orderBy("Sort 1").rangeBetween(Window.unboundedPreceding, Window.currentRow).orderBy(F.asc("Sort 2"),F.asc("Sort 3"),F.asc("Sort 4"))))
df = df.withColumn("days_at_version", F.datediff("creation_date", "lag_creation_date"))
任何帮助将不胜感激。