2012-03-30 18 views
2

Ich habe ein CTE, das die folgenden Datensätze zurückgibt. Wie sollte ich mit der neuen Abfrage fortfahren, so dass alle Datensätze mit GID = NULL die vorherige letzte GID erhalten?tsql - Selbstreferenz

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 

ZB. Datensätze mit ID 5 und 6 haben GID = 3

Antwort

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
;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 
+0

Meine Lösung ist überhaupt nicht richtig –

+0

Es ist nicht offensichtlich, aber ich es jetzt zu sehen. Sie sollten sich wahrscheinlich einen Downvote geben. :) –