I have a table with the following columns:
ID, date, amount, amount2
Column amount2
has values only in the first row.
I need to recursively calculate each row of column amount2
using values from previous row of this column and also column amount
- second row for
amount2
should be: first row value ofamount2
- second row value ofamount
- third row for
amount2
should be: second row value ofamount2
- third row value ofamount
...
I tried to use following code, but it does not work:
SELECT
first_column,
CASE
WHEN second_column IS NULL THEN LAG(first_column, 1, first_column) OVER (ORDER BY row_id) - LAG(first_column, 1, first_column) OVER (ORDER BY row_id DESC)
ELSE second_column
END AS calculated_second_column
from table;
Reproducible example:
CREATE TABLE your_table_name (
id INT,
date DATE,
amount DECIMAL(10,2),
amount1 DECIMAL(10,2)
);
INSERT INTO your_table_name (id, date, amount, amount1)
VALUES
(234, '2020-01-01', 4, 10),
(234, '2020-01-02', 7, NULL),
(234, '2020-01-03', 10, NULL),
(234, '2020-01-04', 15, NULL),
(234, '2020-01-05', 6, NULL);
I expect to have in column amount1; 10, 10-7=3, 3-10=-7, -7-15=-22, -22-6=-28