Is there a way to modify a Lag function to not only go back a previous row, but back to a previous distinct value?
What is currently happening:
Job Date Previous Job Date
----------- ----------------
06/10/2013 -
06/10/2013 06/10/2013
06/10/2013 06/10/2013
07/16/2014 06/10/2013
07/16/2014 07/16/2014
06/07/2015 07/16/2014
06/07/2015 06/07/2015
06/07/2015 06/07/2015
What I want:
Job Date Previous Job Date
----------- ----------------
06/10/2013 -
06/10/2013 -
06/10/2013 -
07/16/2014 06/10/2013
07/16/2014 06/10/2013
06/07/2015 07/16/2014
06/07/2015 07/16/2014
06/07/2015 07/16/2014
Right now i'm using
Lag(a1."Job Date", 1) over (partition by a1."Employee Number" Order By a1."Employee Number")
but this is returning the previous rows record instead of the previous distinct or non-matching record. Is this possible with lag or perhaps a different function?
This is a nifty trick. If you use the range between with "1 PRECEDING" it starts the window at the previous distinct value. Assumes you have some key you want to partition on, but if that's not the case you can just remove the PARTITION BY clause.
Fiddle: https://dbfiddle.uk/3tPzIiDN
Or, the equivalent with correlated subquery