I'm trying to get the lead value based on rankings. Example: for rank #1 (using rank window function), I would need the value of a certain column for rank#2. My problem is, if there's a tie in rank#1 (like 2 rows tied at rank#1) the prior value that i'm getting for row#1 is correct (column value of rank#3) while the prior value on row#2 is getting null.
sample data
rankings, employee, col_date, job, col_a, col_a_date
1 john smith 2022-05-12 a abc 2022-05-12
1 john smith 2022-05-12 b def 2022-05-12
3 john smith 2022-03-27 a ghi 2022-03-27
4 john smith 2021-09-21 a abc 2021-09-21
What I'm getting - actual result
rankings, employee, col_date, job, col_a, col_a_date, prev_col_a
1 john smith 2022-05-12 a abc 2022-05-12 ghi
1 john smith 2022-05-12 b def 2022-05-12 def
3 john smith 2022-03-27 a ghi 2022-03-27 abc
4 john smith 2021-09-21 a abc 2021-09-21 <null>
Expected result
rankings, employee, col_date, job, col_a, col_a_date, prev_col_a
1 john smith 2022-05-12 a abc 2022-05-12 ghi
1 john smith 2022-05-12 b def 2022-05-12 ghi
3 john smith 2022-03-27 a ghi 2022-03-27 abc
4 john smith 2021-09-21 a abc 2021-09-21 <null>
For both rankings #1, i want to get the value of col_a of the next rank which is rank#3.
select *, lead(col_a,1) OVER w as prev_col_a
from (select RANK() OVER (PARTITION BY employee ORDER BY col_a_date DESC) rankings,
*
from table
) WINDOW w AS (
PARTITION BY employee, job
ORDER BY col_a_date DESC
)
order by rankings, col_a_date desc
