I have data like this in SQL Server 2016 database table:
| PERIODE | PERIODE_FORECAST | VALUE |
|---|---|---|
| 2021-08-01 | 2021-01-01 | 51384.673 |
| 2021-08-01 | 2021-02-01 | 44118.129 |
| 2021-08-01 | 2021-03-01 | 43164.446 |
| 2021-08-01 | 2021-04-01 | 38113.745 |
| 2021-08-01 | 2021-05-01 | 37306.956 |
| 2021-08-01 | 2021-06-01 | 38390.359 |
| 2021-08-01 | 2021-07-01 | 42692.390 |
| 2021-08-01 | 2021-08-01 | 39814.047 |
| 2021-08-01 | 2021-09-01 | 0.000 |
| 2021-08-01 | 2021-10-01 | 0.000 |
| 2021-08-01 | 2021-11-01 | 0.000 |
| 2021-08-01 | 2021-12-01 | 0.000 |
I have a condition to fill out the zero values for example :
| PERIODE | PERIODE_FORECAST | VALUE |
|---|---|---|
| 2021-08-01 | 2021-09-01 | 39814.047 * 0.5 |
| 2021-08-01 | 2021-10-01 | (39814.047 * 0.5 ) * 0.7 |
| 2021-08-01 | 2021-11-01 | ((39814.047 * 0.5 ) * 0.7) * 0.5 |
| 2021-08-01 | 2021-12-01 | (((39814.047 * 0.5 ) * 0.7) * 0.5) * n |
I am trying to use the LAG() function, but it didn't come up as I was hoped for.
Query :
SELECT
PERIODE,PERIODE_FORECAST,
CASE
WHEN PERIODE_FORECAST > PERIODE
THEN LAG(VALUE, 1, 0) OVER (ORDER BY PERIODE_FORECAST ASC) * [some function/other column values]
ELSE VALUE
END VALUE
FROM
MyTable
I expected the result :
| PERIODE | PERIODE_FORECAST | VALUE |
|---|---|---|
| 2021-08-01 | 2021-01-01 | 51384.673 |
| 2021-08-01 | 2021-02-01 | 44118.129 |
| 2021-08-01 | 2021-03-01 | 43164.446 |
| 2021-08-01 | 2021-04-01 | 38113.745 |
| 2021-08-01 | 2021-05-01 | 37306.956 |
| 2021-08-01 | 2021-06-01 | 38390.359 |
| 2021-08-01 | 2021-07-01 | 42692.390 |
| 2021-08-01 | 2021-08-01 | 39814.047 |
| 2021-08-01 | 2021-09-01 | 19907.0235 |
| 2021-08-01 | 2021-10-01 | result on 2021-09-01 |
| 2021-08-01 | 2021-11-01 | result on 2021-10-01 |
| 2021-08-01 | 2021-12-01 | result on 2021-11-01 |
How can I use the previous calculated row, and use it in calculated in current row?
Is there any solution or workaround without creating a stored procedure?
Thanks for the answer so far.