I have below data for one store and one product and I need to calculate a column based on another column.
Initial Data set:
store product tran_date audit_date audit_bal inv_value
10001 323232 2020-01-01 null null 5
10001 323232 2020-01-02 2020-01-02 20 31
10001 323232 2020-01-03 null null 13
10001 323232 2020-01-04 null null 6
10001 323232 2020-01-05 null null 21
10001 323232 2020-01-06 null null 17
10001 323232 2020-01-07 null null 6
10001 323232 2020-01-08 null null 34
10001 323232 2020-01-09 null null 35
10001 323232 2020-01-10 2020-01-10 60 17
10001 323232 2020-01-12 null null 6
10001 323232 2020-01-13 null null 9
10001 323232 2020-01-14 null null 5
10001 323232 2020-01-15 null null 29
Logic:
start_stock for the day next to the audit_date should be the audit_bal of audit_date
for remaining days, it should be previous days end_stock
end_stock for the day next to the audit_date should be audit_bal of audit_date + inv_value
for remaining days, it should be start_stock(previous days end_stock) + inv_value
Final Data set should be
store product tran_date audit_date audit_bal inv_value start_stock end_stock
10001 323232 2020-01-01 null null 5 6 11
10001 323232 2020-01-02 2020-01-02 20 31 11 42
10001 323232 2020-01-03 null null 13 20 33
10001 323232 2020-01-04 null null 6 33 39
10001 323232 2020-01-05 null null 21 39 60
10001 323232 2020-01-06 null null 17 60 77
10001 323232 2020-01-07 null null 6 77 83
10001 323232 2020-01-08 null null 34 83 117
10001 323232 2020-01-09 null null 35 117 152
10001 323232 2020-01-10 2020-01-10 120 17 152 169
10001 323232 2020-01-12 null null 6 120 126
10001 323232 2020-01-13 null null 9 126 135
10001 323232 2020-01-14 null null 5 135 140
10001 323232 2020-01-15 null null 29 140 169
I used below query but not getting the correct results
WITH Inv AS (
SELECT *,case when tran_date = date_add(lag_audit_date,1) then lag_audit_bal + inv_value
when date_add(lag_audit_date,1) != tran_date then lag_audit_bal + inv_value
else SUM(inv_value) OVER (partition by store,product ORDER BY tran_date ASC ROWS UNBOUNDED PRECEDING) end as end_stock
FROM
basedata
)
SELECT tran_date,audit_date,audit_bal,lag_audit_date,lag_audit_bal,
case when tran_date = date_add(lag_audit_date,1) then lag_audit_bal
when date_add(lag_audit_date,1) != tran_date then lag_audit_bal
else LAG(end_stock,1,0) OVER (partition by store,product ORDER BY transaction_date ASC) end as start_stock,
inv_val,
end_stock
FROM Inv;
Can someone please help me.