tsql - 自我引用

时间:2012-03-30 09:42:27

标签: tsql common-table-expression

我有一个返回以下记录的CTE。我应该如何处理新查询,以便GID = NULL的所有记录都能获得上一个上一个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。 ID为5和6的记录将具有GID = 3

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

;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 c.id, d.GID, c.value from c 
cross apply 
(select max(GID) GID from c d where c.id >= id) d