I've been told to redo this as people are becoming confused.
I would like to go from this:
RN CalanderDateTime PtID EventDateTime GapinMinutes
1 2017-09-23 08:34 NULL NULL NULL
2 2017-09-23 08:35 NULL NULL NULL
3 2017-09-23 08:36 NULL NULL NULL
4 2017-09-23 08:37 1 2017-09-23 08:37 1
5 2017-09-23 08:38 1 2017-09-23 08:38 4
6 2017-09-23 08:43 1 2017-09-23 08:43 3
7 2017-09-23 08:44 NULL NULL NULL
8 2017-09-23 08:45 NULL NULL NULL
9 2017-09-23 08:46 NULL NULL NULL
10 2017-09-23 08:47 2 2017-09-23 08:47 3
11 2017-09-23 08:48 NULL NULL NULL
12 2017-09-23 08:49 NULL NULL NULL
13 2017-09-23 08:50 NULL NULL NULL
To this
RN CalanderDateTime PtID EventDateTime GapinMinutes
1 2017-09-23 08:34 NULL NULL NULL
2 2017-09-23 08:35 NULL NULL NULL
3 2017-09-23 08:36 NULL NULL NULL
4 2017-09-23 08:37 1 2017-09-23 08:37 1
5 2017-09-23 08:38 1 2017-09-23 08:38 4
6 2017-09-23 08:43 1 2017-09-23 08:43 3
7 2017-09-23 08:44 1 NULL NULL
8 2017-09-23 08:45 1 NULL NULL
9 2017-09-23 08:46 1 NULL NULL
10 2017-09-23 08:47 2 2017-09-23 08:47 3
11 2017-09-23 08:48 2 NULL NULL
12 2017-09-23 08:49 2 NULL NULL
13 2017-09-23 08:50 2 NULL NULL
It almost like smearing the PtID to fill the the next NULL placeholder rows based on the value contained in the GapinMinutes
Best Answer
Previous Requirement
Below query is far improve version of previous one.
let the index be commented now.you don't need the commented CTE1.
New Requirement, (Here your output require is quite change and I am only working on part of your dataset).
Main trick is to implement it seamlessly as part of your main query.
Minor change in query.
Index should not be created by understanding just part of dataset.
Here dataset is very small.But after creating index aim getting one Index Seek and one index scan i.e. query plan seem improve.
IMHO, given outer apply is one best way to do so (80%) .
But with million of rows already,
outer apply
increase the the rows by 50%.inequality operator t.rn>t1.rn
is doing problemMay be it can be implemented from view itself.
It belong to which table and how many rows this table returns ?
Tried to optimize your main query as well as implemented new requirement
This part of query only indicate that what correct should be done,it may not run as it is.you have to fix the bug.