i'm looking for update row using value from row before.
I have something like this:
Group by | Value1 | Value2 | Value2 - expected result |
---|---|---|---|
1 | 0 | 20 | 20 |
1 | 3 | x | 23 |
1 | 5 | x | 28 |
1 | 2 | x | 30 |
2 | 0 | 30 | 30 |
2 | 5 | x | 35 |
2 | 2 | x | 37 |
Value2 = Value2 from row before + value 1 but column "Group by" is importand. If Value2 before is in another group then: Value2 = Value2
Can sameone explain mi how do this update statement? I tried using CTE with LAG function but i always fall in infinite loop.
Code for create table:
create table test
(
[GroupBy] int
, [Date] date
, [Value1] int
, [Value2] int
)
Inserting data:
INSERT INTO test ([GroupBy], [Date] [Value1], [Value2])
VALUES
(1, '2022-01-01', 0, 20),
(1, '2022-01-02', 3, NULL),
(1, '2022-01-03', 5, NULL),
(1, '2022-01-04', 2, NULL),
(2, '2022-01-01', 0, 30),
(2, '2022-01-02', 5, NULL),
(2, '2022-01-03', 2, NULL)
Primary key by: [GroupBy], [Date]