I am trying to create a query that runs against its own results until the results have satisfied what I am looking for. I need to write SQL that will tell me what the next row's [ProjStart]
date should be based on the previous row's [ProjStart]
date + the previous rows [EffortDays]
, per [EmpName]
. The order of each task is based on the [Position]
column partitioned by the [EmpName]
. The trick is that not all rows will have a date until the query tells it to have the [ProjStart]
+[EffortDays]
of the previous row.
Below is a sample table to help create the desired results
DECLARE @aTestTable TABLE
(
Position int,
EmpName VARCHAR(10),
ProjStart DATE,
EffortDays int
);
INSERT INTO @aTestTable VALUES
('1', 'Adam', '2023-05-01',2),
('2', 'Adam', NULL,3),
('3', 'Adam', NULL,1),
('4', 'Adam', NULL,2),
('5', 'Adam', NULL,4),
('6', 'Adam', NULL,3),
('1', 'Bill', '2023-05-07',4),
('2', 'Bill', NULL,5),
('3', 'Bill', NULL,1),
('4', 'Bill', NULL,3),
('5', 'Bill', NULL,6),
('1', 'Bob', '2023-05-10',4),
('2', 'Bob', NULL,2),
('3', 'Bob', NULL,5),
('4', 'Bob', NULL,1),
('5', 'Bob', NULL,1),
('6', 'Bob', NULL,2),
('7', 'Bob', NULL,3),
('1', 'Dave', '2023-04-28',2),
('2', 'Dave', NULL,1),
('3', 'Dave', NULL,5),
('4', 'Dave', NULL,4)
SELECT * FROM @aTestTable
Please let me know if I can provide clarification.
Below is the expected output taking the previous rows [ProjStart]
and adding the previous rows [EffortDays]
for the current rows [ProjStart]
partitioned by [EmpName]
and ordered by [Position]
.
Position EmpName ProjStart EffortDays
1 Adam 2023-05-01 2
2 Adam 2023-05-03 3
3 Adam 2023-05-06 1
4 Adam 2023-05-07 2
5 Adam 2023-05-09 4
6 Adam 2023-05-13 3
1 Bill 2023-05-07 4
2 Bill 2023-05-11 5
3 Bill 2023-05-16 1
4 Bill 2023-05-17 3
5 Bill 2023-05-20 6
1 Bob 2023-05-10 4
2 Bob 2023-05-14 2
3 Bob 2023-05-16 5
4 Bob 2023-05-21 1
5 Bob 2023-05-22 1
6 Bob 2023-05-23 2
7 Bob 2023-05-25 3
1 Dave 2023-04-28 2
2 Dave 2023-04-30 1
3 Dave 2023-05-01 5
4 Dave 2023-05-06 4