I have a table name p_Details with (id,eff_dt,amt,change,month). For each ID and change combination there are 12 records for 12 months. Data looks like below.
id | eff_dt | amt | change | month |
---|---|---|---|---|
100 | 1-Jan | 300 | 1 | 1 |
100 | 1-Jan | 300 | 1 | 2 |
100 | 1-Jan | 300 | 1 | 3 |
100 | 1-Jan | 300 | 1 | 4 |
.. | .. | .. | .. | .. |
100 | 1-Mar | Null | 2 | 1 |
100 | 1-Mar | Null | 2 | 2 |
100 | 1-Mar | 400 | 2 | 3 |
100 | 1-Mar | 400 | 2 | 4 |
.. | .. | .. | .. | .. |
100 | 1-Apr | Null | 3 | 1 |
100 | 1-Apr | Null | 3 | 2 |
100 | 1-Apr | Null | 3 | 3 |
100 | 1-Apr | 500 | 3 | 4 |
If any combination of Id and change is having Null value for a particular month, then amt from same id and same month but from previous change number will be copy over to the present row. Final table should look like below after update.
id | eff_dt | amt | change | month |
---|---|---|---|---|
100 | 1-Jan | 300 | 1 | 1 |
100 | 1-Jan | 300 | 1 | 2 |
100 | 1-Jan | 300 | 1 | 3 |
100 | 1-Jan | 300 | 1 | 4 |
.. | .. | .. | .. | .. |
100 | 1-Mar | 300 | 2 | 1 |
100 | 1-Mar | 300 | 2 | 2 |
100 | 1-Mar | 400 | 2 | 3 |
100 | 1-Mar | 400 | 2 | 4 |
.. | .. | .. | .. | .. |
100 | 1-Apr | 300 | 3 | 1 |
100 | 1-Apr | 300 | 3 | 2 |
100 | 1-Apr | 400 | 3 | 3 |
100 | 1-Apr | 500 | 3 | 4 |
Same Id and month combination can have N number of change numbers. I are trying to use lag()
function but it is not working.
Below is my query which is not giving desired result.
select
case when amt is null then amt_new else amt end as amt,
id,
eff_dt,
change,
month
from (
select
id,
eff_dt,
change,
month,
amt,
LAG(amt) OVER(partition id,month order by change) as amt_new
from p_Details
) e