I have the following table that is created by this code
CREATE TABLE enrollments (
person_id INT,
date DATE,
duration int);
INSERT INTO enrollments (person_id, date, duration)
VALUES
(1, '2004-01-01', 35),
(1, '2004-01-15', 60),
(1, '2004-02-01', 15),
(1, '2004-09-01', 30),
(2, '1994-01-18', 30),
(2, '1994-03-01', 30);
The table looks like:
person_id date duration
1 2004-01-01 35
1 2004-01-15 60
1 2004-02-01 15
1 2004-09-01 30
2 1994-01-18 30
2 1994-03-01 30
I’d like to apply the following logic:
Person 1:
Row 1: 2004-01-01, 35 (no previous row to compare with)
Row 2: 2004-01-15, 60
Previous date + previous duration: 2004-01-01 + 35 days = 2004-02-05. Compare this date with the next row’s date:
Since 2004-02-05 > 2004-01-15, update 2004-01-15 to 2004-02-05
Row 3: 2004-02-01, 15
Previous date + previous duration: 2004-02-05 + 60 days = 2004-04-05
Since 2004-04-05 > 2004-02-01, update 2004-02-01 to 2004-04-05
Row 4: 2004-09-01, 30
Previous date + previous duration: 2004-04-05 + 15 days = 2004-04-20
Since 2004-04-20 < 2004-09-01, no change
I have no idea if this is possible and if it is where to start from. Any help will be greatly appreciated.