Soluzione basata su set per aggiornare nulls per ultimo valore noto nella tabella ordinata

StackOverflow https://stackoverflow.com/questions/4922856

  •  30-10-2019
  •  | 
  •  

Domanda

Per mantenere la mia purezza e onore come Dork del database, desidero aggiornare una serie di dati e galleggianti che hanno alcuni null nella colonna galleggiante in modo tale che ciascun valore nullo venga sostituito dal precedente valore non nullo (da DateTime).

Il mio ambiente è MSSQL 2K8R2.

Spero che il seguente frammento spieghi sufficientemente le mie condizioni di vittoria.

Saluti e grazie.

create table #datesAndValues(
    [Date] datetime,
    Val float);
create table #resultsShouldLookLikeThis(
    [Date] datetime,
    Val float);

insert into #datesAndValues 
values  
    ('1/8/11',1.1),
    ('1/7/11',null),
    ('1/6/11',1.2),
    ('1/5/11',null),
    ('1/4/11',null),
    ('1/3/11',1.3),
    ('1/2/11',null),
    ('1/1/11',null);

/*  
    set based code (no loops!!!) goes here to set nulls
    in the above table to the last known good (not null) value,
    thereby making it look like the following table.
*/

insert into #resultsShouldLookLikeThis
values  
    ('1/8/11',1.1),
    ('1/7/11',1.2),
    ('1/6/11',1.2),
    ('1/5/11',1.3),
    ('1/4/11',1.3),
    ('1/3/11',1.3),
    ('1/2/11',null),
    ('1/1/11',null);

--this will tell us if it worked
select 'In old but not new' as [WhichTable], o.*
from    (select * from #datesAndValues
        except select * from #resultsShouldLookLikeThis) o
union all
select 'In new but not old' as [WhichTable], n.*
from    (select * from #resultsShouldLookLikeThis
        except select * from #datesAndValues) n;

drop table #datesAndValues;
drop table #resultsShouldLookLikeThis;

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top