I have the following table:
CREATE TABLE dbo.Persons
(
[Date] date null,
[PersonId] int null,
[Amount] int null,
[Value] int null
)
And here's some sample data:
INSERT INTO dbo.Persons ([Date], [PersonId], [Amount], [Value])
VALUES
('2020-01-01', 1, 200, NULL),
('2020-01-02', 1, 300, NULL),
('2020-01-03', 1, 400, NULL),
('2020-01-04', 1, 500, NULL),
('2020-01-01', 2, 200, NULL),
('2020-01-02', 2, 300, NULL),
('2020-01-03', 2, 400, NULL),
('2020-01-04', 2, 500, NULL),
('2020-01-01', 3, 0, NULL),
('2020-01-02', 3, 0, NULL),
('2020-01-03', 3, 0, NULL),
('2020-01-04', 3, 0, NULL)
My goal: update all of the values in the [Value] column based on values in other columns AND the previous value in [Value] column. Primary key is date+personId.
Explained in pseudo code, my logic needs to something like:
CASE
WHEN [Amount] > 200 AND previous row value IN [Value] = 1, then 2
WHEN [Amount] > 500 AND previous row value in [Value] = 2, then 3
WHEN [Date] > '2020-01-01' AND [Amount] = 500 AND previous row value in [Value] = 2, then 4
and so on - this captures the general T-SQL code logic..
I only want to update the [Value] column where [Value] is NULL also.
What is the play here? I've read about using LAG, While LOOP, Recursive CTE, etc., but unsure where to go.