Q:

tsql - Self reference

I have a CTE that returns the below records. How should i proceed with the new query so that all records with GID = NULL will get the previous last GID?
ID  GID     VALUE
1   1       Some Value
2   NULL    Some Value
3   2       Some Value
4   3       Some Value
5   NULL    Some Value
6   NULL    Some Value

Eg. Records with ID 5 and 6 will have GID = 3

A:

with C(ID, GID, VALUE) as
(
  select 1,   1,       'Some Value' union all
  select 2,   NULL,    'Some Value' union all
  select 3,   2,       'Some Value' union all
  select 4,   3,       'Some Value' union all
  select 5,   NULL,    'Some Value' union all
  select 6,   NULL,    'Some Value'
)

select C1.ID, 
       C3.GID,
       C1.VALUE
from C as C1
  cross apply
    (select top 1 C2.ID, C2.GID
     from C as C2
     where C2.ID <= C1.ID and
           C2.GID is not null
     order by C2.ID desc) as C3

