I want to set the value of column based on the value of that column in the previous row for a group. Then this updated value will be used in the next row.
I have the following dataframe
id | start_date|sort_date | A | B |
-----------------------------------
1 | 1/1/2017 | 31-01-2015 | 1 | 0 |
1 | 1/1/2017 | 28-02-2015 | 0 | 0 |
1 | 1/1/2017 | 31-03-2015 | 1 | 0 |
1 | 1/1/2017 | 30-04-2015 | 1 | 0 |
1 | 1/1/2017 | 31-05-2015 | 1 | 0 |
1 | 1/1/2017 | 30-06-2015 | 1 | 0 |
1 | 1/1/2017 | 31-07-2015 | 1 | 0 |
1 | 1/1/2017 | 31-08-2015 | 1 | 0 |
1 | 1/1/2017 | 30-09-2015 | 0 | 0 |
2 | 1/1/2017 | 31-10-2015 | 1 | 0 |
2 | 1/1/2017 | 30-11-2015 | 0 | 0 |
2 | 1/1/2017 | 31-12-2015 | 1 | 0 |
2 | 1/1/2017 | 31-01-2016 | 1 | 0 |
2 | 1/1/2017 | 28-02-2016 | 1 | 0 |
2 | 1/1/2017 | 31-03-2016 | 1 | 0 |
2 | 1/1/2017 | 30-04-2016 | 1 | 0 |
2 | 1/1/2017 | 31-05-2016 | 1 | 0 |
2 | 1/1/2017 | 30-06-2016 | 0 | 0 |
Output :
id | start_date|sort_date | A | B | C
---------------------------------------
1 | 1/1/2017 | 31-01-2015 | 1 | 0 | 1
1 | 1/1/2017 | 28-02-2015 | 0 | 0 | 0
1 | 1/1/2017 | 31-03-2015 | 1 | 0 | 1
1 | 1/1/2017 | 30-04-2015 | 1 | 0 | 2
1 | 1/1/2017 | 31-05-2015 | 1 | 0 | 3
1 | 1/1/2017 | 30-06-2015 | 1 | 0 | 4
1 | 1/1/2017 | 31-07-2015 | 1 | 0 | 5
1 | 1/1/2017 | 31-08-2015 | 1 | 0 | 6
1 | 1/1/2017 | 30-09-2015 | 0 | 0 | 0
2 | 1/1/2017 | 31-10-2015 | 1 | 0 | 1
2 | 1/1/2017 | 30-11-2015 | 0 | 0 | 0
2 | 1/1/2017 | 31-12-2015 | 1 | 0 | 1
2 | 1/1/2017 | 31-01-2016 | 1 | 0 | 2
2 | 1/1/2017 | 28-02-2016 | 1 | 0 | 3
2 | 1/1/2017 | 31-03-2016 | 1 | 0 | 4
2 | 1/1/2017 | 30-04-2016 | 1 | 0 | 5
2 | 1/1/2017 | 31-05-2016 | 1 | 0 | 6
2 | 1/1/2017 | 30-06-2016 | 0 | 0 | 0
Group is of id and date
Column C is to derived based on column A and B.
If A == 1 and B == 0 then C is derived C from previous row + 1.
There are some other conditions as well but I am struggling with this part.
Assuming we have a column sort_date in dataframe.
I tried the following query :
SELECT
id,
date,
sort_date,
lag(A) OVER (PARTITION BY id, date ORDER BY sort_date) as prev,
CASE
WHEN A=1 AND B= 0 THEN 1
WHEN A=1 AND B> 0 THEN prev +1
ELSE 0
END AS A
FROM
Table
This Is what I did for UDAF
val myFunc = new MyUDAF
val w = Window.partitionBy(col("ID"), col("START_DATE")).orderBy(col("SORT_DATE"))
val df = df.withColumn("C", myFunc(col("START_DATE"), col("X"),
col("Y"), col("A"),
col("B")).over(w))
P.S : I am using Spark 1.6