I have a PySpark DataFrame and I would like to get the second highest value of ORDERED_TIME (DateTime Field yyyy-mm-dd format) after a groupBy applied to 2 columns, namely CUSTOMER_ID and ADDRESS_ID.
A customer can have many orders associated with an address and I would like to get the second most recent order for a (customer,address) pair
My approach was to make a window and partition according to CUSTOMER_ID and ADDRESS_ID, sort by ORDERED_TIME
sorted_order_times = Window.partitionBy("CUSTOMER_ID", "ADDRESS_ID").orderBy(col('ORDERED_TIME').desc())
df2 = df2.withColumn("second_recent_order", (df2.select("ORDERED_TIME").collect()[1]).over(sorted_order_times))
However, I get an error saying ValueError: 'over' is not in list
Could anyone suggest the right way to go about solving this problem?
Please let me know if any other information is needed
Sample Data
+-----------+----------+-------------------+
|USER_ID |ADDRESS_ID| ORDER DATE |
+-----------+----------+-------------------+
| 100| 1000 |2021-01-02 |
| 100| 1000 |2021-01-14 |
| 100| 1000 |2021-01-03 |
| 100| 1000 |2021-01-04 |
| 101| 2000 |2020-05-07 |
| 101| 2000 |2021-04-14 |
+-----------+----------+-------------------+
Expected Output
+-----------+----------+-------------------+-------------------+
|USER_ID |ADDRESS_ID| ORDER DATE |second_recent_order
+-----------+----------+-------------------+-------------------+
| 100| 1000 |2021-01-02 |2021-01-04
| 100| 1000 |2021-01-14 |2021-01-04
| 100| 1000 |2021-01-03 |2021-01-04
| 100| 1000 |2021-01-04 |2021-01-04
| 101| 2000 |2020-05-07 |2020-05-07
| 101| 2000 |2021-04-14 |2020-05-07
+-----------+----------+-------------------+-------------------
